如何从网站中的每个 .aspx 网页中删除 .aspx?以下方法有效,但仅适用于网站的根目录,定义长文件夹结构效率低下且困惑。
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);
}
以下内容在没有尾部斜杠的情况下工作,但是我如何强制它有一个尾部斜杠,因为没有任何东西可以跟随包罗万象的routeURL?
routes.MapPageRoute("RemASPx", "{*file}", "~/{file}.aspx");
最佳答案
保留此路由设置:
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("RemoveASPx", "{*file}", "~/{file}.aspx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
添加此重写:
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();
}
}
以上代码块:
- 检查网址是否为 null 或出于不言自明的原因为空
- 检查 URL 是否为目录,因为您不想重写目录(如果应用程序默认状态中有任何内容,则会导致重定向循环,因为目录中会添加尾部斜杠)
- 检查网址是否以斜杠结尾,从而判断是否需要将其删除
- 使用 301 响应(最合适的响应 - 特别是对于 SEO);添加 header 会导致重定向
关于c# - 从所有网页中删除 .aspx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129639/