简体   繁体   English

删除尾部斜杠-不使用IIS重写ASP.net

[英]Remove Trailing Slash - Not using IIS rewrite ASP.net

How would I remove a trailing slash without using the IIS rewrite module? 我如何在不使用IIS重写模块的情况下删除斜杠?

I assume I can add something to the RegisterRoutes function in the global.asax.cs file? 我假设可以在global.asax.cs文件中的RegisterRoutes函数中添加一些内容?

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // Do Not Allow URL to end in trailing slash
        string url = HttpContext.Current.Request.Url.AbsolutePath;
        if (string.IsNullOrEmpty(url)) return;

        string lastChar = url[url.Length-1].ToString();
        if (lastChar == "/" || lastChar == "\\")
        {
            url = url.Substring(0, url.Length - 1);
            Response.Clear();
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", url);
            Response.End();
        }
    }

Using an extension method on the HttpContext.Current.Request makes this reusable for other similar issues such as redirecting to avoid duplicate content URLs for page 1: HttpContext.Current.Request上使用扩展方法可使此方法可重用于其他类似问题,例如重定向以避免页面1的重复内容URL。

public static class HttpRequestExtensions
{
    public static String RemoveTrailingChars(this HttpRequest request, int charsToRemove)
    {
        // Reconstruct the url including any query string parameters
        String url = (request.Url.Scheme + "://" + request.Url.Authority + request.Url.AbsolutePath);

        return (url.Length > charsToRemove ? url.Substring(0, url.Length - charsToRemove) : url) + request.Url.Query;
    }
}

This can then be called as needed: 然后可以根据需要调用它:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    String requestedUrl = HttpContext.Current.Request.Url.AbsolutePath;
    // If url ends with /1 we're a page 1, and don't need (shouldn't have) the page number
    if (requestedUrl.EndsWith("/1"))
        Response.RedirectPermanent(Request.RemoveTrailingChars(2));

    // If url ends with / redirect to the URL without the /
    if (requestedUrl.EndsWith("/") && requestedUrl.Length > 1)
        Response.RedirectPermanent(Request.RemoveTrailingChars(1));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM