Reputation: 115
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
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:
Upvotes: 3