简体   繁体   中英

Url rewriting in asp.net core 2.0

I want to rewrite the url

http://localhost:56713/Home/UserDetails?Code=223322

with

http://localhost:56713/223322

I have written below in StartUp.cs but it is not working

var rewrite = new RewriteOptions()
  .AddRewrite(@"{$1}", "Home/UserDetails?Code={$1}",true);

You need a Regular Expression on the first parameter on AddRewrite function.

var rewrite = new RewriteOptions().AddRewrite(
     @"^Home/UserDetails?Code=(.*)",  // RegEx to match Route
     "Home/{$1}",                     // URL to rewrite route
     skipRemainingRules: true         // Should skip other rules
);

This link maybe can help with more examples https://docs.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?tabs=aspnetcore2x

Adding a rule to match @"{$1}" won't work. The term $1 represents a value parsed using RegEx. You haven't executed any RegEx so you're effectively telling it to "rewrite my URL whenever the URL is null ". Clearly, that isn't very likely.

You want to match the incoming URL using this regular expression:

@"^Home/UserDetails?Code=(\d+)"

The (\\d+) tells RegEx to match "one or more digits" and store it as a variable. Since this is the only variable included in the parens, the value is stored in $1 .

You then want to rewrite the URL using the value parsed using that regex:

"Home/$1"

You pass these two strings into the AddRewrite method:

AddRewrite(
    @"^Home/UserDetails?Code=(\d+)", // RegEx to match URL
    "Home/$1", // URL to rewrite
    true // Stop processing any aditional rules
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM