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://learn.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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With