Docs:处理 ASP.NET Core 中的错误
两种 404 错误:
- 通过 Id 找不到指定的内容或信息
-
处理 Id 错误
处理 Id 错误需设置 StatusCode 并返回对应的错误页。
public IActionResult Details(int id){var student = _studentRepository.GetStudent(id);if (student == null){Response.StatusCode = 404;return View("StudentNotFound", id);}var homeDetailsViewModel = new HomeDetailsViewModel{Student = student,PageTitle = "学生详细信息"};return View(homeDetailsViewModel);}
错误页:
@model int@{ViewBag.Title = "404 找不到内容";}<div class="alert alert-danger mt-1 mb-1"><h4>404 Not Found 错误</h4><hr /><h6>查询不到 ID 为 @Model 的学生信息</h6></div><a asp-controller="Home" asp-action="Index" class="btn btn-outline-success" style="width: auto">返回学生列表</a>
统一处理
三种统一处理的方式:
- UseStatusCodePages
- UseStatusCodePagesWithRedirects
- UseStatusCodePagesWithReExecute
在 Startup 里面启用 UseStatusCodePagesWithRedirects:
if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseStatusCodePagesWithRedirects("/Error/{0}");}
ErrorController:
public class ErrorController : Controller{[Route("Error/{statusCode}")]public IActionResult HttpStatusCodeHandler(int statusCode){switch (statusCode){case 404:ViewBag.ErrorMessage = "抱歉,您访问的页面不存在";break;}return View("NotFound");}}
NotFound 展示错误信息,并提供链接返回首页:
@{ViewBag.Title = "页面不存在";}<h1>@ViewBag.ErrorMessage</h1><a asp-controller="Home" asp-action="Index">点击此处返回首页</a>
UseStatusCodePagesWithRedirects vs UseStatusCodePagesWithReExecute
Redirects:
- 会发出重定向请求,而地址栏中的 URL 将发生更改
- 当发生真实错误时,它返回一个 success status(200),它在语义上是不正确的
ReExecute:
- 重新执行管道请求并返回原始状态码(如 404)
- 由于它是重新执行管道请求,而不是发出重定向请求,所以我们地址栏中会保留原始 URL
地址栏保留原始 URL:
