本文介绍了ASP.NET MVC Controller.OnException 未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本控制器类,我在其中覆盖了 Controller.OnException 处理程序方法,以便为将从此类继承的某些类型的控制器(这些是将返回 JSON 结果的 API 控制器)提供通用错误处理).当控制器引发异常时,永远不会调用 OnException 方法.有没有人看到我做错了什么,或者有没有更好的方法来处理这种情况?

I have a base controller class where I'm overriding to the Controller.OnException handler method in order to provide a generic error handling for certain types of controllers that will inherit from this class (these are API controllers that will return JSON results). The OnException method never gets called when an exception gets raised by the controller. Does anyone see what I am doing wrong, or is there a better way to handle this situation?

使用 MVC 1.0

基类:

public class APIController : Controller
    {

        protected override void OnException(ExceptionContext filterContext)
        {
           //This is never called
            filterContext.Result =
                new JsonResult();
            base.OnException(filterContext);
        }


    }

继承类:

public class MyController : APIController
    {
public AjaxResult ForcedException()
        {
            throw new SystemException();
        }
}

推荐答案

如果我正确理解您的问题 - 您的异常必须在 OnException 中标记为已处理".试试这个:

If I understand your question correctly - your Exception must be marked as "handled" in your OnException. Try this:

filterContext.ExceptionHandled = true;

这篇关于ASP.NET MVC Controller.OnException 未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 14:59