Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 886
Techno Crave Avatar asked Mar 07 '23 14:03

Techno Crave


2 Answers

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

like image 143
gblmarquez Avatar answered Mar 16 '23 04:03

gblmarquez


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
);
like image 21
Marc LaFleur Avatar answered Mar 16 '23 06:03

Marc LaFleur