示例
CRUDExample项目新建Middlewares文件夹,下面新建ExceptionHandlingMiddleware.cs(VS中有Middleware模板)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Serilog;
using System.Threading.Tasks;
namespace CRUDExample.Middlewares
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly IDiagnosticContext _diagnosticContext;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger, IDiagnosticContext diagnosticContext)
{
_next = next; //represents the subsequent middleware
_logger = logger;
_diagnosticContext = diagnosticContext;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
_logger.LogError("{ExceptionType}{ExceptionMassage}", ex.InnerException.GetType().ToString(), ex.InnerException.Message);
}
else
{
_logger.LogError("{ExceptionType}{ExceptionMassage}", ex.GetType().ToString(), ex.Message);
}
}
httpContext.Response.StatusCode = 500;
await httpContext.Response.WriteAsync("Error occurred");
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class ExceptionHandlingMiddlewareExtensions
{
public static IApplicationBuilder UseExceptionHandlingMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExceptionHandlingMiddleware>();
}
}
}
Program.cs
var app = builder.Build();
app.UseSerilogRequestLogging();
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandlingMiddleware();
}
注意
对于测试环境,按照上面的代码,如果有错误会显示详细的错误信息到页面;
对于生产环境,如果不使用自定义中间件抓取报错信息,页面会显示类似400、500等报错,使用自定义中间件后可以在页面展示自定义的容易理解的报错信息,比如“Error occurred”。
launchSettings.json中可以设置运行环境:
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
Gitee获取源码:
https://gitee.com/huang_jianhua0101/asp.-net-core-8.git
标签:app,Exception,Handling,Middleware,next,httpContext,ex,logger,public From: https://blog.csdn.net/KevinHuang2088/article/details/139533952