获取先前在应用程序c#中引发的异常?

获取先前在应用程序c#中引发的异常?,c#,asp.net,asp.net-core,C#,Asp.net,Asp.net Core,我编写了一个中间件,在回调上检查响应是否为500。如果是500,我想返回抛出的异常。如何获取应用程序中抛出的异常 Startup.cs ... app.UseMiddleware<APIExceptionMiddleware>(); // Add MVC to the request pipeline. app.UseMvc(); ... 。。。 app.UseMiddleware(); //将MVC添加到请求管道。 app.UseMvc(); ... APIExceptio

我编写了一个中间件,在回调上检查响应是否为500。如果是500,我想返回抛出的异常。如何获取应用程序中抛出的异常

Startup.cs

...
 app.UseMiddleware<APIExceptionMiddleware>();

// Add MVC to the request pipeline.
app.UseMvc();
...
。。。
app.UseMiddleware();
//将MVC添加到请求管道。
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);
        }
    }
公共类APIExceptionMiddleware
{
private readonly RequestDelegate\u next;
公共APIExceptionMiddleware(RequestDelegate下一步)
{
_下一个=下一个;
}
公共异步任务调用(HttpContext上下文)
{
context.Response.onStart(
回调:(状态)=>
{   
HttpResponse响应=(HttpResponse)状态;
如果(response.StatusCode==500)
{
//想在这里获取异常,将其转换为JSON响应,将其放在response.Body中,但不确定如何访问异常。
返回response.WriteAsync(“发生错误”);
}
返回Task.FromResult(空);
},状态:context.Response);
wait_next.Invoke(上下文);
}
}
因此,当请求进入UseMvc()时,会引发一个异常。我可以使用app.UseDeveloperException();并获得一个带有stacktrace和exception的友好HTML页面

我几乎想重复这一点,但对于我的应用程序来说,这是一个友好的JSON api响应。因此,如果抛出500,我将使用中间件将其转换为一个漂亮的json响应,并通过api请求将其作为响应发送出去。我的问题是如何在中间件中获取此异常


如果UseDeveloperException()正在执行此操作,那么我是否也可以执行此操作?

请查看。。。特别是查看
调用(HttpContext上下文)
(如下所示)。不要使用您当前正在添加的默认中间件,而是使用您自己已经启动的中间件。这将非常类似于
DeveloperExceptionPageMiddleware
:捕获任何异常,但不是返回错误页面,而是根据需要格式化JSON响应

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next(context);
    }
    catch (Exception ex)
    {
        _logger.LogError(0, ex, "An unhandled exception has occurred while executing the request");

        if (context.Response.HasStarted)
        {
            _logger.LogWarning("The response has already started, the error page middleware will not be executed.");
            throw;
        }

        try
        {
            context.Response.Clear();
            context.Response.StatusCode = 500;

            await DisplayException(context, ex);

            if (_diagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.UnhandledException"))
            {
                _diagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.UnhandledException", new { httpContext = context, exception = ex });
            }

            return;
        }
        catch (Exception ex2)
        {
            // If there's a Exception while generating the error page, re-throw the original exception.
            _logger.LogError(0, ex2, "An exception was thrown attempting to display the error page.");
        }
        throw;
    }
}

没有context.error您的意思是没有公开的属性或它为null?没有context error属性。作用域中有Server.GetLastError()吗?不确定没有,因为这是红隼,这正是我要找的。请记住,泄露你系统的信息是一种安全风险。是的,我有一些我想要传递的信息,不是全部。我将使用一个决定来通过那些我想要的,忽略其他的。谢谢