how to do url rewrite in C#.net. implemented in asp.net4.0 version

how to do url rewrite in C#.net. implemented in asp.net4.0 version

Url rewriting is just to display a friendly and readable url instead of a comlex or unfriendly url.

Suppose there is a url in your website just like below:

http://sharepointcafe.net/Page.aspx?userid=23456

The disadvantages of above mentioned url are:

1. This is not a friendly url.
2. The url does nt looks descent.
3. Last but the major thing is this url is not readable by Google and other search engine.

So, if your website contains url like above then there is no meaning of your content of that page because it will not be indexed by google.

So, how can it be avoid and how it can be re write in a seo friendly and readable url.

In asp.net 3.0 it was not an easy task to complete. But in asp.net4.0 it is very easy.

I am explaining this for asp.net 4.0 version.

First add a Global.asax file in your project.

Add the reference of System.Web.Routing in your project.
And then add this <%@ Import Namespace="System.Web.Routing" %>

Add a method like below:

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("ForumRouting", "Page/{user_id}", "~/Page.aspx");
     
    }
Now call this method from Application_Start like below:

 void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RegisterRoutes(RouteTable.Routes);
    }

Let me explain about code :

 routes.MapPageRoute("ForumRouting", "Page/{user_id}", "~/Page.aspx");

First parameter in MapPageRoute method is just a name, you can pass any string.
Second parameter contains 2 part. Page is the name of your page and userid is your query string name.
Third parameter is the physical path of Page with correct extension.

Now in your aspx add link like this:
<a href="<%# WriteUrl(Eval("userid").ToString())%>" title = <%#Eval("user_name")%> id = "test"><%#Eval("user_name")%></a>

Now you call the method WriteUrl in code behind:

 protected string WriteUrl(string userid)
    {
return Page.GetRouteUrl("ForumRouting", new { userid= user_id}); //user_id is from Global.asax file.
//userid will be your url value (i.e. new url)
}

Now if you want to manage the url, then in the code behind of page where you want to redirect write below code:

string Get urlvalue = Page.RouteData.Values["user_id"]).ToString();

Thats done.
So, from now its up to you how you are going to implement this.

Comments

Popular

C# 6.0 New Features

SharePoint Interview Questions and Answers

Calling ASP.Net WebMethod using jQuery AJAX

What is Cloud Computing - A guide for beginners