我有一些中間件寫在回調中檢查響應是否是500.如果是500我想返回拋出的異常。如何獲取應用程序中引發的異常?獲取早期在應用程序c#中拋出的異常?
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();並用stacktrace和exception獲得一個友好的HTML頁面。
我想幾乎重複一遍,但使它成爲我的應用程序的友好JSON API響應。所以,如果一個500被拋出,我正在使用中間件,我將把它變成一個漂亮的json響應,並通過api請求將其作爲響應發送出去。我的問題是如何在中間件中獲取此異常?
如果UseDeveloperException()正在做,它不應該我能夠嗎?
context.Error? – pnm
有沒有context.Error – allencoded
你的意思是沒有暴露的財產或它是空的? – pnm