Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewriting URLs in ASP.NET/C#

Tags:

url

asp.net

How can I use the below code to call an account as

http://www.domain.ext/madcoder

instead of

http://www.domain.ext/index.aspx?key=madcoder

As my madcoder is my primary search key to fetch databse

I found the following code but couldn't understand how to use it. Anybody please help me.

<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
  <match url="^([^/]+)/?$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Rewrite" url="?p={R:1}" />
</rule>

EDIT 1

I tried modifying my web.config file in the below way which is giving me error

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <rule name="RewriteUserFriendlyURL1" stopProcessing="true">
        <match url="^([^/]+)/?$" />
        <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="index.aspx?key={R:1}" />
    </rule>
</configuration>
like image 537
Mad coder. Avatar asked Dec 11 '25 21:12

Mad coder.


2 Answers

If you are using .net 4.0 it can be MUCH easier.

.net 4 Webforms Routing

like image 101
Jordan Avatar answered Dec 14 '25 19:12

Jordan


What about:

<action type="Rewrite" url="index.aspx?key={R:1}" />

About the match/replace tags: the match-url is applied on the url after the domain slash (in your case, after http://www.domain.ext/). The parentheses are for grouping and catching, so ([^/]+) will match anything not containing a slash, right after the domain. It may contain a trailing slash, but anything else is currently disallowed.

The rewrite action can contain a literal string, but can also contain {R:xxx} references, which refer to anything you caught in the parentheses earlier. In this case, the string madcoder.

like image 21
Abel Avatar answered Dec 14 '25 19:12

Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!