我将 HTTPContext.RewritePath 用于没有扩展名且文件系统上不存在的路径。我希望它返回我的自定义 404 页面。我在 Windows 7 上使用 IIS 7.5、.Net 4 和集成管道。
重写发生在一个名为 RewriteExampleModule 的 HTTPModule 中。如下所示。
using System;
using System.Web;
public class RewriteExampleModule : IHttpModule
{
public RewriteExampleModule()
{
}
private void context_PostAuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
String path = context.Request.RawUrl;
if (path.IndexOf("/edit/") > -1)
{
path = path.Replace("/edit/", "/");
context.RewritePath(path);
}
}
public bool IsReusable
{
get { return true; }
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PostAuthorizeRequest += new EventHandler(context_PostAuthorizeRequest);
}
}
它在模块部分中配置如下,
<modules runAllManagedModulesForAllRequests="true">
<add name="RewriteExampleModule" type="RewriteExampleModule" />
</modules>
对不存在 /asdf 的 /edit/asdf 的请求的结果是 500 错误。它应该是404,但不是。
下列的,
IIS 7.5 – 应用 Windows Server 2008 R2 SP1 后无扩展 URI 处理的重大变化?
我已经删除了 ExtensionlessUrlHandler,现在得到了 404。但是,响应的主体是空的。连同下面显示的重写模块是我完整的 web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="true" />
<modules runAllManagedModulesForAllRequests="true">
<add name="RewriteExampleModule" type="RewriteExampleModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
</handlers>
<httpErrors existingResponse="Replace" errorMode="Custom">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="/404error.aspx" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
</configuration>
使用此配置调用
/编辑/asdf
其中 /asdf 不存在返回 404 状态代码,但没有在 httpErrors 下的 web.config 中指定的自定义内容。
为什么404主体是空的?没有重写 /edit/ 的任何其他路径都可以。