ExceptionFilter OnException未被调用

时间:2017-07-11 00:00:27

标签: c# asp.net-mvc exception-handling

我是使用exceptionfilters的新手。

点击链接:https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling#httpresponserexception

我创建了一个类

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

然后我在我的控制器上使用了一个方法的属性。我还没有在全球范围内添加过滤器,因为我希望它现在能用于单一方法。

public class HomeController : Controller
{
    [NotImplExceptionFilter]
    public void Test()
    {
        throw new NotImplementedException("This method is not implemented");
    }
}

但每次我抛出错误时都不会调用OnExepction。请让我知道我错过了什么

2 个答案:

答案 0 :(得分:0)

我认为您的问题是,您正在继承Controller班而不是ApiController,正如文档所说。

由于您在此属性中使用System.Web.Http命名空间,因此它仅适用于Api控制器。

如果你想使用其他控制器,你需要添加另一个异常过滤器属性,但在这种情况下不要使用System.Web.Http但使用System.Web.Mvc命名空间,而另一部分将是几乎相同的代码( 只有一些小改动

再次覆盖OnException并在那里制作逻辑,但请记住这两种方式在实际向用户显示错误消息方面有所不同。第一个使用响应来显示消息,另一个必须以不同的方式实现。可能会看一下here

答案 1 :(得分:0)

您的另一个问题是您缺少System.Web.Mvc.FilterAttribute,一旦应用了它,它应该会按预期触发。 (前提是您已更改为使用IExceptionFilter / ExceptionContext而不是已声明的ExceptionFilterAttribute / HttpActionExecutedContext。

示例:

[AttributeUsage(AttributeTargets.Method]
    public class NotImplExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext) {
        {
            if (filterContext.Exception is NotImplementedException)
        {
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}
相关问题