asp.net-mvc ASP.net MVC [HandleError] 没有捕获异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/619582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:23:10  来源:igfitidea点击:

ASP.net MVC [HandleError] not catching exceptions

asp.net-mvcexception-handlinghandleerror

提问by Craig Stuntz

In two different application, one a custom the other the sample MVC application you get with a new VS2008 MVC project, [HandleError] is not catching exceptions.

在两个不同的应用程序中,一个是自定义的,另一个是您通过新的 VS2008 MVC 项目获得的示例 MVC 应用程序,[HandleError] 没有捕获异常。

In the sample application I have:

在示例应用程序中,我有:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        throw new Exception();
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

which is just the default controller with an exception being thrown for testing.

这只是默认控制器,抛出异常进行测试。

But it doesn't work. Instead of going to the default error.aspx page it shows the debug information in the browser.

但它不起作用。它不会转到默认的 error.aspx 页面,而是在浏览器中显示调试信息。

The problem first cropped up in a custom application I'm working on which led me to test it with the sample application. Thinking it had something to do with changes I made in the custom application, I left the sample application completely unchanged with the exception (yuck) of the throw in the index method.

该问题首先出现在我正在处理的自定义应用程序中,这导致我使用示例应用程序对其进行测试。认为这与我在自定义应用程序中所做的更改有关,我将示例应用程序完全保持不变,除了 index 方法中 throw 的异常(糟糕)。

I'm stumped. What am I missing?

我难住了。我错过了什么?

回答by Craig Stuntz

In Web.config, change customErrors:

在 Web.config 中,更改 customErrors:

<system.web>
  <customErrors mode="On">
  </customErrors>

If mode is either Off or RemoteOnly, then you will see the yellow screen of death instead of the custom error page. The reasoning is that developers usually want the more detailed information on the yellow screen of death.

如果 mode 为 Off 或 RemoteOnly,那么您将看到黄色死亡屏幕而不是自定义错误页面。原因是开发人员通常希望在死亡黄屏上获得更详细的信息。

回答by Simon_Weaver

Important:Be careful that your error page itself does not have an error on it!

重要提示:请注意您的错误页面本身没有错误!

If it does you'll end up with that ASP.NET custom error page and end up going round in circles and tearing your hair out. Just strip everything out of the page that could possibly cause an error and test it.

如果是这样,你最终会得到那个 ASP.NET 自定义错误页面,并最终绕圈子把你的头发扯掉。只需从页面中删除可能导致错误的所有内容并对其进行测试。

Also with respect to 'customErrors' being ON or OFF there are several contributing factors to whether or not the friendly error page (your Errors.aspx) page will be shown or not.

此外,关于“customErrors”是ON还是OFF,是否显示友好错误页面(您的Errors.aspx)页面有几个影响因素。

See this blog(except below)

请参阅此博客(以下除外)

HttpContext.IsCustomErrorEnabled - looks at three different sources

  1. The web.config's <deployment> section's retail property. This is a useful property to set when deploying your application to a production server. This overrides any other settings for custom errors.
  2. The web.config's <customErrors> section's mode property. This setting indicates whether custom errors are enabled at all, and if so whether they are enabled only for remote requests.
  3. The HttpRequest object's IsLocal property. If custom errors are enabled only for remote requests, you need to know whether the request is from a remote computer.

HttpContext.IsCustomErrorEnabled - 查看三个不同的来源

  1. web.config 的 <deployment> 部分的零售属性。这是在将应用程序部署到生产服务器时设置的有用属性。这会覆盖自定义错误的任何其他设置。
  2. web.config 的 <customErrors> 部分的 mode 属性。此设置指示是否完全启用自定义错误,如果是,是否仅对远程请求启用它们。
  3. HttpRequest 对象的 IsLocal 属性。如果仅对远程请求启用自定义错误,则需要知道该请求是否来自远程计算机。

The idea here is that you can have 'customErrors' turned OFF during development - when you do want to see the errors, and then enable it for production only.

这里的想法是你可以在开发过程中关闭“customErrors”——当你确实想看到错误时,然后只为生产启用它。

This MSDN articlediscusses the attribute further.

这篇MSDN 文章进一步讨论了该属性。

回答by Palani

Another reason for this problem may be ,

这个问题的另一个原因可能是,

In Template MVC Application (generated by VS2008 / VS2008 Express) , Error.aspx (generated by VS) uses Master Page.

在 Template MVC Application(由 VS2008 / VS2008 Express 生成)中,Error.aspx(由 VS 生成)使用 Master Page。

If Master Page access any ViewData it will throw null reference Exception , then the error.aspx won't be shown.

如果母版页访问任何 ViewData 它将抛出空引用 Exception ,则不会显示 error.aspx 。

Use this Simple code as your Error.aspx , it will solve the problem, (along with CustomErrors=On )

使用此简单代码作为您的 Error.aspx ,它将解决问题,(以及 CustomErrors=On )

<%@ Page Language="C#"  Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<%= Model.Exception.Message %>

回答by RunnerRick

I have struggled with this as well and I believe I understand the problem now.

我也为此苦苦挣扎,我相信我现在明白了这个问题。

In short the requirements for having [HandleError]work as expected are:

简而言之,[HandleError]按预期工作的要求是:

You must enable custom errors in web.configAND you must also specify where your error view is in the <customErrors>tag.

您必须在web.config 中启用自定义错误,并且还必须指定错误视图在<customErrors>标记中的位置。

Example:

例子:

<customErrors mode="On" defaultRedirect="Error" />

Leaving off the defaultRedirect="Error"part will instead yield a 500 error in the browser--NOT the ASP.NET error page (YSOD).

离开该defaultRedirect="Error"部分将在浏览器中产生 500 错误——而不是 ASP.NET 错误页面 (YSOD)。

Also you do not have to be in Release mode. I tested this with a Debug build and it worked fine.

此外,您不必处于发布模式。我使用 Debug 版本对此进行了测试,效果很好。

My environment was Visual Studio 2010 using .NET 4 and the standard, "ASP.NET MVC 2 Web Application" project template.

我的环境是 Visual Studio 2010,使用 .NET 4 和标准的“ASP.NET MVC 2 Web 应用程序”项目模板。

What confused me was the MSDN documentation for the HandleErrorAttribute Class. It doesn't explicitly say you must turn on custom errors in web.config. And I assumed all I needed was the [Handle Error]attribute.

让我感到困惑的是 HandleErrorAttribute 类的 MSDN 文档。它没有明确说明您必须在web.config 中打开自定义错误。我假设我需要的只是[Handle Error]属性。

回答by Agat

There is some silly situation which once happened with me, so might be helpfull for someone.

我曾经发生过一些愚蠢的情况,所以可能对某人有帮助。

Be sure that you've added <customErrors mode="On" />to the correctweb.configfile.

确保您已添加<customErrors mode="On" />正确的web.config文件中。



Sometimes (especially, when you work with something like Resharper, and open your files with typing their name, but not via Solution Explorer), you can simply open a web.config either from Views folder or even from another project.

有时(尤其是,当您使用 Resharper 之类的工具,并通过键入文件名打开文件时,而不是通过解决方案资源管理器打开文件时),您可以简单地从 Views 文件夹甚至从另一个项目打开 web.config。

回答by Leniel Maccaferri

Watch out: in my case I was trying to get the HandleErrorattribute to catch an exceptionthrown inside the Controllers constructor! Of course it won't catch it. The HandleErrorattribute only catches exceptions thrown inside Controlleractions. It's right there in the MSDN page (should've paid more attention to that):

注意:在我的情况下,我试图获取HandleError属性以捕获exceptionControllers构造函数中抛出的异常!它当然不会抓住它。该HandleError属性仅捕获在Controlleractions 中抛出的异常。它就在 MSDN 页面中(应该更加注意这一点):

Represents an attribute that is used to handle an exception that is thrown by an action method.

表示用于处理由操作方法引发的异常的属性。

Another thing that was happening is that the Controller's OnException(ExceptionContext exceptionContext)overridden method was never being called. Again: of course it would not be called since I was throwing an exception inside the Controller's constructor.

发生的另一件事是控制器的OnException(ExceptionContext exceptionContext)重写方法从未被调用。再说一遍:当然不会调用它,因为我在Controller的构造函数中抛出了异常。

I spent 1 hour trying to figure this out. :o) Hope it helps the next soul...

我花了1个小时试图弄清楚这一点。:o) 希望它能帮助下一个灵魂......

As a hint: remember that the HandleErrorattribute only catches 500errors. For the other ones you should declare the <customErrors>section in Web.config:

作为提示:请记住,该HandleError属性仅捕获500错误。对于其他的,您应该在 中声明该<customErrors>部分Web.config

<customErrors mode="On">
  <error statusCode="403" redirect="~/403" />
  <error statusCode="404" redirect="~/404" />
</customErrors>