【发布时间】:2014-11-18 11:47:38
【问题描述】:
我正在努力在我的web.config 中正确设置httpErrors 部分以捕获ASP.NET MVC errors 和IIS errors。我收到 403 状态代码和空白页。我通过在 URL 中输入不正确的 URL 和文件名来测试 404 错误,例如:
www.mywebsite.com/test
www.mywebsite.com/test.html
我正在使用最新版本的ASP.NET MVC 5。此 Web 应用程序在 IIS 7.5 上运行,应用程序池使用 integrated mode。
这就是我的web.config 在应用程序根目录下的样子(这是我目前拥有的全部):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
<!-- ...and so forth... -->
</assemblyBinding>
</runtime>
</configuration>
我的global.asax.cs 文件:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
protected void Application_Error()
{
// Break point has been set here for testing purposes
}
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
// Break point has been set here for testing purposes
}
}
}
我的错误控制器:
public class ErrorController : Controller
{
public ActionResult Index()
{
// Break point has been set here for testing purposes
Response.StatusCode = 500;
return View();
}
public ActionResult Forbidden()
{
// Break point has been set here for testing purposes
Response.StatusCode = 403;
return View();
}
public ActionResult NotFound()
{
// Break point has been set here for testing purposes
Response.StatusCode = 404;
return View();
}
}
它们在Views文件夹中有对应的视图。
我的错误控制器中永远不会遇到我的断点。我不明白为什么?我在 Stackoverflow 上查看了许多示例,这就是每个人都建议我这样做的方式。给定我的代码,何时无法达到断点?所发生的只是 403 错误状态和空白白页。 Application_Error() 和 Application_EndRequest() 中的断点被命中,但错误控制器中的断点未命中。
我可以在Application_Error() 和Application_EndRequest() 中编写代码,让我设置错误控制器和操作方法,但如果我可以使用web.config,为什么要这样做?这也应该有效?
【问题讨论】:
-
你能检查一下提琴手中的 URL 流吗,我在我的示例应用程序中实现了同样的东西,对我来说它在 404 上工作正常,请确保你没有实现任何异常过滤器。
-
Fiddler 中的状态码也显示 404,我没有添加过滤器。我在哪里检查这个?我为此创建了一个新的空 MVC Web 应用程序。如果我将其更改为显示错误的 html 静态页面,那么它 100% 正确。当我使用控制器时,它显示为空白。
-
@BrendanVogt 我遇到了完全相同的问题。关键的相似之处是触发 404 ExecuteURL 时带有空白页面的 403 Forbidden HTTP 响应。你有想过这个吗?
标签: c# asp.net asp.net-mvc asp.net-mvc-4 iis