ASP.NET 4: 允许对URL中的特殊字符串放宽要求

在做 URL Rewrite 时可能遇到这类问题,即想要使用的 Rewrite 后的目标 URL 中会含有特殊字符,或者说不能直接映射到操作系统的文件系统允许的文件名格式,比如以 “.” 结尾等等。如果不做特殊处理的话则 ASP.NET 引擎会报 "CheckSuspiciousPhysicalPath” 的错误。

解决办法:

1. ASP.NET 版本小于4.0的情况,可以在 Global.asax.cs 中处理 PreSendRequestHeaders 事件,例如:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpResponse response = this.Context.Response;
HttpRequest request = this.Context.Request;
if (request.RawUrl.EndsWith("."))
{
response.ClearContent();
response.StatusCode = 200;
response.StatusDescription = "OK";
response.SuppressContent = false;
response.ContentType = "text/plain";
response.Write("You have dot at the end of the url, this is allowed, but not by ASP.NET, but I caught you!");
response.End();
}
}

2. ASP.NET 版本 >= 4.0,在 web.config 中添加一个设置即可:

<configuration>
<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true"/>
<!-- ... your other settings ... -->
</system.web>
</configuration>

参考:

http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx

http://stackoverflow.com/questions/1126735/problem-with-a-url-that-ends-with-20

posted on 2011-04-12 15:54  NeilChen  阅读(838)  评论(0编辑  收藏  举报

导航