在Startup.cs文件中,将中间件的顺序从下往上进行排列,并确保异常处理中间件是最先被注册的。示例代码如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); }
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMiddleware();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
其中,ExceptionMiddleware是自定义的异常处理中间件,代码示例如下:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger
public ExceptionMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await context.Response.WriteAsync(new ErrorDetails()
{
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error from the custom middleware."
}.ToString());
}
}
在以上示例代码中,ExceptionMiddleware仅仅是针对服务器端异常的处理,还需要在客户端代码中进行错误处理,代码示例如下:
try { // 执行某些代码块 } catch (error) { console.error(error); // 显示错误信息到视图上 }
使用以上方法可以实现ASP.Net Core应用中的全局异常处理。