sha*_*ear 3 .net c# asp.net-mvc .net-core asp.net-core
我在我的 .Net Core 应用程序中创建了一个新的 Exception 中间件。整个应用程序中的所有异常都在此处捕获并记录。我想要的是从异常中间件返回一个 IActionResult 类型,如 InternalServerError() 或 NotFound() ,而不是像下面那样做 response.WriteAsync 。
控制器方法:
public async Task<IActionResult> Post()
{
//Do Something
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
中间件:
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
}));
}
}
Run Code Online (Sandbox Code Playgroud)
IActionResult是来自 MVC 的东西,所以它只在 MVC 管道中可用(包括 Razor Pages)。就在MVC中间件终止之前,它会执行使用这些行动的结果ExecuteAsync。然后该方法负责将该响应写入HttpContext.Response.
因此,在自定义中间件中,您不能只设置操作结果并执行它,因为您不在 MVC 管道中运行。但是,有了这些知识,您可以自己简单地执行结果。
比方说,你要执行NotFoundResult这是什么Controller.NotFound()造成的。因此,您创建该结果并ExecuteAsync使用 . 该执行器将能够执行该结果对象并写入响应:
var result = new NotFoundResult();
await result.ExecuteAsync(new ActionContext
{
HttpContext = context,
});
Run Code Online (Sandbox Code Playgroud)