删除尾随斜杠-不使用IIS重写ASP.net
本文关键字:IIS 重写 ASP net 删除 | 更新日期: 2023-09-27 18:21:57
如果不使用IIS重写模块,如何删除尾部斜杠?
我想我可以在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();
}
}
在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;
}
}
这可以根据需要调用:
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));
}