我一直在使用Owin自託管和的WebAPI寫簡單的服務器:如何覆蓋Owin中的默認未處理異常輸出?
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響應:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Attempted to divide by zero.</ExceptionMessage>
<ExceptionType>System.DivideByZeroException</ExceptionType>
<StackTrace>
...
</StackTrace>
</Error>
但我想不同的輸出 - 那麼我怎麼能覆蓋這個?
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
}
}
}
並把它掛在啓動時:
你在找什麼樣的產出? – abatishchev 2015-02-24 05:56:18