为什么Response.StatusCode =(int)HttpStatusCode.NotFound给我一般的错误处理程序?

时间:2016-05-18 21:18:36

标签: asp.net-mvc asp.net-mvc-3

我使用以下代码捕获并将404错误重定向到Error controller \ views。

Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "HttpError";
routeData.Values["exception"] = exception;          

Response.StatusCode = 500;
//if http 404 redirect to http404 action
if (httpException != null)
{
    Response.StatusCode = httpException.GetHttpCode();
    switch (Response.StatusCode)
    {
        case 404:
            routeData.Values["action"] = "Http404";
            break;
    }
}

在错误控制器中,如果我设置Response.StatusCode =(int)HttpStatusCode.NotFound我得到通用错误处理程序,而不是我返回的视图。这似乎只在生产中发生。有什么想法吗?

[AllowAnonymous]
public ActionResult Http404()
{
    //this line causes generic error handler
    Response.StatusCode = (int)HttpStatusCode.NotFound;

    var viewModel = new ErrorViewModel
    {
        Description = "Hmm, the page you're looking for can't be found"
    };

    return View("Error", viewModel);
}

1 个答案:

答案 0 :(得分:0)

如果您在控制器的操作方法中设置自定义StatusCode,并且想要覆盖默认错误处理,则需要执行以下操作之一:

  • 在控制器方法
  • 中设置Response.TrySkipIisCustomErrors = true
  • 在Web.config中定义以下内容:

    <system.webServer> <httpErrors existingResponse="PassThrough"></httpErrors> </system.webServer>

此处提供更多详细信息:https://stackoverflow.com/a/22477783/459102