Ich habe ein Projekt, AspNet WebApi 2 in Owin gehostet mit Microsoft.Owin.Host.SystemWeb, die Ausnahme Behandlung mit beiden Owin Middleware implementiert und Hinzufügen eines IExceptionHandler über die httpConfiguration wie in dieser post beschrieben.AspNet WebApi gehostet mit Owin.Host.SystemWeb Ausnahme Middleware fängt keine POST-Anfragen
Im folgenden Projekt habe ich einen Controller, der Ausnahmen mit Endpunkten für Get und Post auslöst. Wenn ich eine Get-Anfrage erstelle, bekomme ich die erwartete Antwort von der Owin-Ausnahme-Middleware;
Wenn jedoch eine Postanforderung macht die Middleware übersprungen wird, und die zurückgegebene folgenden;
Es scheint, die Post-Anforderung die Middleware überspringt und gibt ein 500, bevor es die Owin Exception-Handler zu machen. Ich möchte in der Lage sein, die Post-Anfrage Ausnahme zu fangen und sie zu protokollieren. Irgendeine Idee, wie das gemacht werden sollte? und was verursacht das unterschiedliche Verhalten zwischen Post und Get?
Beispiel Repo- und Code-Snippets;
https://github.com/timReynolds/WebApiExceptionDemo
OwinExceptionHandlerMiddleware
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}");
});
}
}
Startup
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);
}