asp.netregexurl-rewritingurlrewriter.neturlrewriter

ASP.NET UrlRewriter - How to Write RegEx for Root?


I have been trying to use UrlRewriter (Intelligencia.UrlRewriter.dll) in a test project.

My rewrite statement is as in the following:

<rewrite url="~/Sample/(.+)" to="~/Sample.aspx?Test=$1"/>

This statement works great for a URL like:

http://localhost:4188/RewriteTest/Sample/12345

or, let's say:

http://RewriteTest.com/Sample/12345

And, I can retrieve the value "12345" in Sample.aspx file as:

Label1.Text = "Test: " + Request.QueryString["Test"];

And when I hit the root link, it successfully displays the Default.aspx:

http://localhost:4188/RewriteTest/ or http://RewriteTest.com/

What I want to accomplish is taking the "Sample" off the regex statement, so that I can directly hit http://RewriteTest.com/12345 and display Sample.aspx by retrieving "12345" value. And, when the root is hit http://RewriteTest.com/ it will simply display Default.aspx as it is now.

Is it possible? Can the regex statement be updated to something else for this purpose?

Thank you,

Niyazi


Solution

  • If your ID code is always going to be 5 digit number then you could have clamped the regex to that:

    <rewrite url="^~/([\d]{5})$" to="~/Sample.aspx?Test=$1"/>
    

    Or a variable length number:

    <rewrite url="^~/([\d]+)$" to="~/Sample.aspx?Test=$1"/>