What is URL Rewriting and how to implement it?

Add Global.asax file. Using Global.asax u can rewrite ur URL. just add this function.

void Application_BeginRequest(object sender, EventArgs e)
{
    //in this file u can write code for rewrite URL
    if (url is not in ur root path)
    {
        httpContext.RewritePath(reWritePage1);
    }
}

Or

void Application_BeginRequest(object sender, EventArgs e)
{
    System.Web.HttpContext httpContext = HttpContext.Current;
    String currentURL = httpContext.Request.Path.ToLower();
    //Creates the physical path on the server
    string physicalPath = httpContext.Server.MapPath(currentURL.Substring(currentURL.LastIndexOf("/") + 1));
    //checks to see if the file does not exsists.
    if (!System.IO.File.Exists(physicalPath) && !currentURL.EndsWith("webresource.axd"))
    {
        string reWritePage = "Default2.aspx";
        httpContext.RewritePath(reWritePage);
    }
}

OR

void Application_BeginRequest(object sender, EventArgs e)
{
    string CurrentPath = Request.Path.ToLower();
    char[] ch = {'/'};
    string[] str = CurrentPath.Split(ch, StringSplitOptions.RemoveEmptyEntries);
    HttpContext MyContext = HttpContext.Current;
    if (CurrentPath.Contains("/preview/"))
    {
        if (str.Length == 2)
        {
            MyContext.RewritePath("/Forms/Preview.aspx?web=" + str[1]);
        }
        else
        {
            Response.Redirect("/");
        }
    }
    else if (CurrentPath.Contains("/members/userprofile/"))
    {
        if (str.Length == 3)
        {
            MyContext.RewritePath("/members/UserProfile.aspx?uid=" + str[2]);
        }
        else
        {
            Response.Redirect("/");
        }
    }
}
Tagged . Bookmark the permalink.

Leave a Reply