c# - 从所有网页中删除 .aspx

标签 c# asp.net routes webforms

如何从网站中的每个 .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();
    }
}

以上代码块:

  1. 检查网址是否为 null 或出于不言自明的原因为空
  2. 检查 URL 是否为目录,因为您不想重写目录(如果应用程序默认状态中有任何内容,则会导致重定向循环,因为目录中会添加尾部斜杠)
  3. 检查网址是否以斜杠结尾,从而判断是否需要将其删除
  4. 使用 301 响应(最合适的响应 - 特别是对于 SEO);添加 header 会导致重定向

关于c# - 从所有网页中删除 .aspx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129639/

相关文章:

c# - 响应状态码不表示成功 : 404 (Not Found) with owin library

ASP.NET AJAX Function.createDelegate vs Function.createCallback?

asp.net - 在 ASP MVC5 中对同一操作定义属性路由后如何重定向到操作

javascript - angularjs - $state.go 更改 url 但不加载 html 页面

php - Silex 上的绑定(bind)方法

c# - 将属性本身传递给 C# 中的参数

c# - Web API OData EnableLowerCamelCase

c# - 使用 SOAP 数据包调试 Web 服务

C# 停止执行直到事件引发

c# - 如何在 C# ASP.NET (VS 2010) 中包含另一个 Web 文件