我正在努力在我的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应用程序在具有使用integrated mode
的应用程序池的IIS 7.5
上运行。
这是我的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,为什么还要这样做呢?这也应该起作用吗?
发布于 2014-11-18 20:12:03
伙计,你提到statusCode是404,那你怎么能期望是200 OK呢?:)
只需从操作方法中删除Response.StatusCode = 404;
行
下面的代码应该可以工作
public ActionResult NotFound()
{
return View();
}
https://stackoverflow.com/questions/26993606
复制相似问题