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

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

问题描述

 命名空间OwinSelfHostingTest 
{
使用System.Threading;
使用System.Web.Http;
使用Microsoft.Owin.Hosting;
使用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(con​​fig);
}
}

public class Server
{
private ManualResetEvent resetEvent = new ManualResetEvent(false);
私人线程;

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

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

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

}

是控制器中的异常,那么Owin会返回XML响应:

 < Error> 
< Message>发生错误。< / Message>
< ExceptionMessage>尝试除以零。< / ExceptionMessage>
< ExceptionType> System.DivideByZeroException< / ExceptionType>
< StackTrace>
...
< / StackTrace>
< / Error>

但是我想要不同的输出 - 那么我如何覆盖这个?

解决方案

通过创建一个OWIN MiddleWare并将其挂接到管道中:

  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)
{
//自定义内容
}
}
}

并在启动时挂起:

  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(con​​fig);
}
}

任何未处理的异常都将被您的中间件并允许您自定义输出结果。



需要注意的重要事项:如果正在托管的东西具有自己的异常处理逻辑就像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();
        }
    }

}

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?

解决方案

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
      }
   }
 }

And hook it on startup:

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.

An important thing to note: if the thing being hosted has an exception handling logic of it's own, as WebAPI does, exceptions will not propagate. This handler is meant for any exception which goes by unhandeled by the underlying service being hosted.

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

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