如何覆盖默认未处理的异常输出Owin? [英] How to override default unhandled exception output in Owin?

查看:146
本文介绍了如何覆盖默认未处理的异常输出Owin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Owin自托管和书面简单的服务器的WebAPI:

I've written simple server using Owin Self-hosting and WebApi:

namespace OwinSelfHostingTest
{
    using System.Threading;
    using System.Web.Http;
    using Microsoft.Owin.Hosting;
    using Owin;

    public class Startup
    {
        public void Configuration(IAppBuilder builder)
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                "Default",
                "{controller}/{id}",
                new { id = RouteParameter.Optional }
                );

            builder.UseWebApi(config);
        }
    }

    public class Server
    {
        private ManualResetEvent resetEvent = new ManualResetEvent(false);
        private Thread thread;

        private const string ADDRESS = "http://localhost:9000/";

        public void Start()
        {
            this.thread = new Thread(() =>
                {
                    using (var host = WebApp.Start<Startup>(ADDRESS))
                    {
                        resetEvent.WaitOne(Timeout.Infinite, true);
                    }
                });
            thread.Start();
        }

        public void Stop()
        {
            resetEvent.Set();
        }
    }

}

像这样的

当在控制器例外,那么Owin返回XML响应:

When there is exception in controller, then Owin returns XML response like this:

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>Attempted to divide by zero.</ExceptionMessage>
    <ExceptionType>System.DivideByZeroException</ExceptionType>
    <StackTrace> 
        ...
    </StackTrace>
</Error>

但我想不同的输出 - 那么,如何可以重写此

But i want different output - so how can i override this?

推荐答案

您通过创建OWIN中间件和它挂钩到管道这样做的:

You do so by creating an OWIN MiddleWare and hooking it into the pipeline:

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

   public override async Task Invoke(IOwinContext context)
   {
      try
      {
          await Next.Invoke(context);
      }
      catch(Exception ex)
      {
          // Custom stuff here
      }
   }
 }

和它挂在启动:

public class Startup
{
    public void Configuration(IAppBuilder builder)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            "Default",
            "{controller}/{id}",
            new { id = RouteParameter.Optional }
            );

        builder.Use<CustomExceptionMiddleware>().UseWebApi(config);
    }
}

这样的未处理的异常会被你的中间件被捕获并允许您自定义输出结果。

That way any unhandled exception will be caught by your middleware and allow you to customize the output result.

这篇关于如何覆盖默认未处理的异常输出Owin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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