第一步:添加异常中间件来拦截请求处理管道

    1. if (env.IsDevelopment())
    2. {
    3. app.UseDeveloperExceptionPage();
    4. }
    5. else
    6. {
    7. app.UseExceptionHandler("/Error");
    8. app.UseStatusCodePagesWithReExecute("/Error/{0}");
    9. //app.UseStatusCodePagesWithRedirects("/Error/{0}");
    10. }

    第二步:完善 ErrorController 并允许匿名访问

    1. [AllowAnonymous]
    2. [Route("Error")]
    3. public IActionResult Error()
    4. {
    5. var exceptionHandlerPathFeature= HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    6. ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
    7. ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
    8. ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
    9. return View();
    10. }

    第三步:完成错误视图代码

    1. @{
    2. ViewBag.Title = "异常错误页面";
    3. }
    4. <h3>程序请求时,发生了一个内部错误,我们会反馈给开发团队,尽快解决该问题</h3>
    5. <h5>请通过 ltm@xxx.org 与我们取得联系</h5>
    6. <hr />
    7. <h3>错误详情:</h3>
    8. <div class="alert alert-danger">
    9. <h5>异常路径:</h5>
    10. <hr />
    11. <p>@ViewBag.ExceptionPath</p>
    12. </div>
    13. <div class="alert alert-danger">
    14. <h5>异常内容:</h5>
    15. <hr />
    16. <p>@ViewBag.ExceptionMessage</p>
    17. </div>
    18. <div class="alert alert-danger">
    19. <h5>异常堆栈跟踪:</h5>
    20. <hr />
    21. <p>@ViewBag.StackTrace</p>
    22. </div>