Owin的WebAPI服务无视ExceptionFilter [英] Owin WebApi service ignoring ExceptionFilter

查看:378
本文介绍了Owin的WebAPI服务无视ExceptionFilter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

堆栈,

有关某种原因,我Owin的WebAPI服务是无视我们的自定义异常处理程序。我在下面的 asp.net异常处理文档。下面是简化的实现细节(擦净商业秘密的东西)。

可以有人指出我俯瞰什么?

自定义异常过滤器:

 公共类CustomExceptionFilter:ExceptionFilterAttribute
{
   公共覆盖无效onException的(HttpActionExecutedContext actionExecutedContext)
   {
       actionExecutedContext.Response.Status code =的HTTPStatus code.NotFound;
       actionExecutedContext.Response.Content =新的StringContent(...我的定制业务... ...消息在这里......);
   }
}

在启动过程中:

  VAR过滤器=新CustomExceptionFilter();
config.Filters.Add(过滤器);
appBuilder.UseWebApi(配置);

测试控制器:

  [CustomExceptionFilter]
公共类的TestController:ApiController
{
    公共无效的get()
    {
        抛出新的异常(); //这是一个简化。
                               //这是真的抛出埋
                               //下实现的细节层
                               //使用的控制器。
    }
}


解决方案

您可以尝试实施的全局错误的ASP.NET Web API 2 处理。
这样,您将获得的Web API中间件全局错误处理程序,而不是在OWIN pippeline其他中间件,如授权之一。

如果你想实现一个globlal错误处理中间件,,的这个链接可能定向您。

我希望它能帮助。

修改

关于对@ t0mm13b的评论,我给基于第一这个 链接的。

对于全局的错误处理,你可以写一个自定义的和简单的中间件只是通过在管道中的执行流程以下中间件,但在尝试块。

如果有在管道下面中间件的一个未处理的异常,它会在捕捉捕捉块:

 公共类GlobalExceptionMiddleware:OwinMiddleware
{
    公共GlobalExceptionMiddleware(OwinMiddleware下一个):基地(下)
    {}    公共覆盖异步任务调用(IOwinContext上下文)
    {
        尝试
        {
            等待Next.Invoke(背景);
        }
        赶上(异常前)
        {
            //你的处理逻辑
        }
    }
}

Startup.Configuration()方法,如果你想处理异常的所有其他中间件在首位中间件添加到管道中。

 公共类启动
{
    公共无效配置(IAppBuilder应用程序)
    {
        app.Use< GlobalExceptionMiddleware>();
        //注册其他中间件
    }
}

由于在第二的托马斯Lycken A /二百零五万四千七百五十四分之三千四百三十一万二千零十六> 这个的链接,你可以用它来处理的Web API中间件产生的异常创建一个类实现 IExceptionHandler 刚抛出捕获的异常,这样的全局异常处理中间件会抓住它:

 公共类PassthroughExceptionHandler:IExceptionHandler
{
    公共任务HandleAsync(ExceptionHandlerContext背景下,的CancellationToken的CancellationToken)
    {
        //不只是抛出异常;这会毁了堆栈跟踪
        VAR信息= ExceptionDispatchInfo.Capture(context.Exception);
        info.Throw();
    }
}

和不要忘了替换 IExceptionHandler 在Web API中间件配置过程中:

  config.Services.Replace(typeof运算(IExceptionHandler),新PassthroughExceptionHandler());

Stack,

For some reason my Owin WebApi service is ignoring our custom exception handler. I'm following documentation for asp.net exception handling. Here are the simplified implementation details (scrubbed out business proprietary stuff).

Can you someone point out what I'm overlooking?

Custom exception filter:

public class CustomExceptionFilter : ExceptionFilterAttribute
{
   public override void OnException(HttpActionExecutedContext actionExecutedContext)
   {
       actionExecutedContext.Response.StatusCode = HttpStatusCode.NotFound;
       actionExecutedContext.Response.Content = new StringContent("...my custom business...message...here...");
   }
}

During startup:

var filter = new CustomExceptionFilter();
config.Filters.Add(filter);
appBuilder.UseWebApi(config);

Test controller:

[CustomExceptionFilter]
public class TestController: ApiController
{
    public void Get()
    {
        throw new Exception(); // This is a simplification. 
                               // This is really thrown in buried 
                               // under layers of implementation details
                               // used by the controller.
    }
}

解决方案

You can try to implement Global Error Handling in ASP.NET Web API 2. This way you will get a global error handler for Web API middleware, but not for other middlewares in OWIN pippeline, like authorization one.

If you want to implement a globlal error handling middleware, this, this and this links could orientate you.

I hope it helps.

EDIT

Regarding on @t0mm13b's comment, I'll give a little explanation based on the first this link from Khanh TO.

For global error handling you can write a custom and simple middleware that just pass the execution flow to the following middleware in the pipeline but inside a try block.

If there is an unhandled exception in one of the following middlewares in the pipeline, it will be captured in the catch block:

public class GlobalExceptionMiddleware : OwinMiddleware
{
    public GlobalExceptionMiddleware(OwinMiddleware next) : base(next)
    { }

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        }
        catch (Exception ex)
        {
            // your handling logic
        }
    }
}

In the Startup.Configuration() method, add the middleware in first place to the pipeline if you want to handle exceptions for all other middlewares.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<GlobalExceptionMiddleware>();
        //Register other middlewares
    }
}

As pointed by Tomas Lycken in the second this link, you can use this to handle exceptions generated in Web API middleware creating a class that implements IExceptionHandler that just throws the captured exception, this way the global exception handler middleware will catch it:

public class PassthroughExceptionHandler : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        // don't just throw the exception; that will ruin the stack trace
        var info = ExceptionDispatchInfo.Capture(context.Exception);
        info.Throw();
    }
}

And don't forget to replace the IExceptionHandler during the Web API middleware configuration:

config.Services.Replace(typeof(IExceptionHandler), new PassthroughExceptionHandler());

这篇关于Owin的WebAPI服务无视ExceptionFilter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆