Tim*_*lds 4 c# asp.net-web-api asp.net-web-api2 owin-middleware
我有一个使用 Microsoft.Owin.Host.SystemWeb 托管在 Owin 中的 AspNet WebApi 2 的项目,该项目使用 Owin 中间件并通过 httpConfiguration 添加 IExceptionHandler 来实现异常处理,如本文所述。
在下面的项目中,我有一个控制器,它会抛出带有 Get 和 Post 端点的异常。创建 get 请求时,我从 Owin 异常中间件获得了预期的响应;
但是,当发出 post 请求时,中间件将被跳过并返回以下内容;
看来 post 请求会跳过中间件并在进入 Owin 异常处理程序之前返回 500。我希望能够捕获发布请求异常并记录它。知道应该如何做吗?是什么导致了 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";
}
}
Run Code Online (Sandbox Code Playgroud)
异常记录器示例
public class ExampleExceptionLogger : IExceptionLogger
{
public async Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
{
await Task.Run(() =>
{
Console.WriteLine($"Example Exception Logger {context}");
});
}
}
Run Code Online (Sandbox Code Playgroud)
启动
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);
}
Run Code Online (Sandbox Code Playgroud)
事实证明这是由于使用了不正确的 Cors 包造成的。通过 IIS 托管时,应使用 EnableCors 配置,但在 Owin 内部应使用 Owin 特定的 Cors 包。
因此,为了使其正常工作,我删除Microsoft.AspNet.WebApi.Cors并使用了Microsoft.Owin.Cors它,并对 ; 进行了以下更改appBuilder:
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.UseCors(CorsOptions.AllowAll); // Use Owin Cors
appBuilder.UseWebApi(httpConfiguration);
}
Run Code Online (Sandbox Code Playgroud)
这里总结了有关实现这一点的详细信息。
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |