【问题标题】:Remove .aspx from all webpages从所有网页中删除 .aspx
【发布时间】:2013-04-14 07:46:07
【问题描述】:

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

【问题讨论】:

标签: c# asp.net routing webforms


【解决方案1】:

保留此路由设置:

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. 出于不言自明的原因检查 url 是否为空或为空
  2. 检查 URL 是否为目录,因为您不想重写目录(如果应用程序默认状态中的任何内容将导致重定向循环,因为在目录中添加了尾部斜杠)
  3. 检查 URL 是否以斜杠结尾,因此是否需要删除
  4. 使用了301响应(最合适的响应——尤其是对于SEO);添加的标头会导致重定向

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2015-01-10
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2012-01-07
    相关资源
    最近更新 更多