user2303264
user2303264

Reputation: 115

Remove .aspx from all webpages

How would I go about removing .aspx from every .aspx webpage in a website? The following works, but only for the root of the website, and defining long folder structures is inefficient and messy.

void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("RemASPx", "{file}", "~/{file}.aspx");
}

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

The following works with no trailing slash, but how would I force it to have a trailing slash as nothing can follow the catch-all routeURL?

routes.MapPageRoute("RemASPx", "{*file}", "~/{file}.aspx");

Upvotes: 2

Views: 602

Answers (1)

TODOName
TODOName

Reputation: 138

Keep this routing setup:

void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("RemoveASPx", "{*file}", "~/{file}.aspx");
}

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

Add this rewrite:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    string url = HttpContext.Current.Request.Url.AbsolutePath;
    if (string.IsNullOrEmpty(url) ||
        System.IO.Directory.Exists(Server.MapPath(url)))
        return;

    if (url.EndsWith("/"))
    {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", url.Substring(0, url.Length - 1));
        Response.End();
    }
}

Above code block:

  1. checks if the url is null or empty for self-explanatory reasons
  2. checks if the URL is a directory, because you don't want to rewrite a directory (if anything in the apps default state a redirect loop will be caused, as a trailing slash is added to directories)
  3. check if URL ends with a slash, thus if it needs to be removed
  4. 301 response used (most suitable response - especially for SEO); added header causes the redirect

Upvotes: 3

Related Questions