Mad coder.
Mad coder.

Reputation: 2175

Rewriting URLs in ASP.NET/C#

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>

Upvotes: 3

Views: 594

Answers (3)

Tanmay Nehete
Tanmay Nehete

Reputation: 2198

try this this work successfully write following code in web config

 <system.web>
        <urlMappings enabled="true">
          <add url="~/Index" mappedUrl="Index.aspx?key={R:1}"/>

        </urlMappings>
    </system.web>

in c# write following code

Response.redirect("~/index")

or else u can also pass your value

Upvotes: 1

Jordan
Jordan

Reputation: 2758

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

.net 4 Webforms Routing

Upvotes: 3

Abel
Abel

Reputation: 57149

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.

Upvotes: 2

Related Questions