【发布时间】:2020-04-05 05:25:13
【问题描述】:
我在我的 .Net Core 应用程序中创建了一个新的异常中间件。整个应用程序中的所有异常都在此处捕获和记录。我想要的是从异常中间件返回一个像 InternalServerError() 或 NotFound() 这样的 IActionResult 类型,而不是像下面那样做 response.WriteAsync。
控制器方法:
public async Task<IActionResult> Post()
{
//Do Something
return Ok();
}
中间件:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var response = context.Response;
var statusCode = (int)HttpStatusCode.InternalServerError;
var message = exception.Message;
var description = exception.Message;
response.ContentType = "application/json";
response.StatusCode = statusCode;
await response.WriteAsync(JsonConvert.SerializeObject(new ErrorResponse
{
Message = message,
Description = description
}));
}
}
【问题讨论】:
标签: c# .net asp.net-mvc asp.net-core .net-core