【发布时间】:2016-02-12 07:14:16
【问题描述】:
我在回调中编写了一些中间件,用于检查响应是否为 500。如果是 500,我想返回抛出的异常。如何获取应用程序中引发的异常?
Startup.cs
...
app.UseMiddleware<APIExceptionMiddleware>();
// Add MVC to the request pipeline.
app.UseMvc();
...
APIExceptionMiddleware.cs:
public class APIExceptionMiddleware
{
private readonly RequestDelegate _next;
public APIExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Response.OnStarting(
callback: (state) =>
{
HttpResponse response = (HttpResponse)state;
if (response.StatusCode == 500)
{
// want to grab exception here turn it into JSON response place it in the response.Body but not sure how I access the exception.
return response.WriteAsync("An Error Occured");
}
return Task.FromResult<object>(null);
}, state: context.Response);
await _next.Invoke(context);
}
}
所以当请求进入 UseMvc() 时,我抛出了一个异常。我可以使用 app.UseDeveloperException();并获得一个带有堆栈跟踪和异常的友好的 HTML 页面。
我几乎想重复一遍,但要让它成为我的应用程序的友好的 JSON api 响应。因此,如果抛出 500,我将使用中间件将其转换为漂亮的 json 响应,并通过 api 请求将其作为我的响应发送出去。我的问题是如何在中间件中获取这个异常?
如果 UseDeveloperException() 正在做,我不应该也能做到吗?
【问题讨论】:
-
没有上下文。错误
-
你的意思是没有暴露的属性或者它是空的?
-
没有上下文错误属性。
-
Server.GetLastError() 是否在范围内?
-
不确定不是,因为这是红隼
标签: c# asp.net asp.net-core