Monday, April 27, 2015

URL Routing to remove .aspx extension from URL in C#.net

Global.asax File:

static void RegisterRoutes()
{
System.Web.Routing.RouteTable.Routes.Add("login",new System.Web.Routing.Route("login", new RouteHandler("~/login.aspx")));
System.Web.Routing.RouteTable.Routes.Add("Main", new System.Web.Routing.Route("Main", new RouteHandler("~/Main.aspx")));
System.Web.Routing.RouteTable.Routes.Add("Message", new System.Web.Routing.Route("Message", new RouteHandler("~/Message.aspx")));
}

public class RouteHandler : IRouteHandler
{
string _virtualPath;
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
foreach (var value in requestContext.RouteData.Values)
{
requestContext.HttpContext.Items[value.Key] = value.Value;
}
return (Page)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page));
}
}

Web.config: