Microsoft.Owin.Host.SystemWeb を使用して、Owin でホストされている AspNet WebApi 2 を使用するプロジェクトを持っています。
以下のプロジェクトでは、Get と Post の両方のエンドポイントで例外をスローするコントローラーがあります。get リクエストを作成すると、Owin 例外ミドルウェアから予期される応答が返されます。
ただし、投稿リクエストを行うと、ミドルウェアはスキップされ、次が返されます。
post リクエストがミドルウェアをスキップして 500 を返し、Owin 例外ハンドラに到達するようです。投稿リクエストの例外をキャッチしてログに記録できるようにしたい。これをどのように行うべきか考えていますか?post と get の間で動作が異なる原因は何ですか?
リポジトリとコード スニペットの例。
https://github.com/timReynolds/WebApiExceptionDemo
OwinExceptionHandlerミドルウェア
public class OwinExceptionHandlerMiddleware
{
private readonly AppFunc _next;
public OwinExceptionHandlerMiddleware(AppFunc next)
{
if (next == null)
{
throw new ArgumentNullException("next");
}
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
try
{
await _next(environment);
}
catch (Exception ex)
{
try
{
var owinContext = new OwinContext(environment);
HandleException(ex, owinContext);
return;
}
catch (Exception)
{
Console.WriteLine("Exception while generating the error response");
}
throw;
}
}
private void HandleException(Exception ex, IOwinContext context)
{
var request = context.Request;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ReasonPhrase = "Internal Server Error from OwinExceptionHandlerMiddleware";
}
}
ExampleExceptionLogger
public class ExampleExceptionLogger : IExceptionLogger
{
public async Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
await Task.Run(() =>
{
Console.WriteLine($"Example Exception Logger {context}");
});
}
}
起動
public void Configuration(IAppBuilder appBuilder)
{
var httpConfiguration = new HttpConfiguration();
httpConfiguration.Services.Replace(typeof(IExceptionHandler), new ExampleExceptionHandler());
httpConfiguration.Services.Add(typeof(IExceptionLogger), new ExampleExceptionLogger());
httpConfiguration.MapHttpAttributeRoutes();
httpConfiguration.EnableCors();
appBuilder.UseOwinExceptionHandler();
appBuilder.UseWebApi(httpConfiguration);
}