第37章 抽离跨域异常处理管道中间件之CorsExceptionHandlerMiddleware
public class CorsExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
public CorsExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
// 处理异常,设置响应状态码和内容
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/problem+json";
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An error occurred while processing your request.",
Detail = ex.Message,
Instance = context.Request.Path.Value
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(problemDetails));
}
}
}
// 在Startup.cs中配置CorsExceptionHandlerMiddleware
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
// 添加CORS异常处理中间件
app.UseMiddleware<CorsExceptionHandlerMiddleware>();
// ...
}
这个代码实例展示了如何创建一个自定义的CORS异常处理中间件,并在Startup.cs
中配置它。当下游中间件链中的中间件抛出异常时,这个自定义中间件会捕获异常,设置合适的HTTP状态码和响应内容,这有助于提高API服务的可靠性和安全性。
评论已关闭