示例
新建HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace CRUDExample.Controllers
{
public class HomeController : Controller
{
[Route("Error")]
public IActionResult Error()
{
return View(); //Views/Shared/Error
}
}
}
Views/Shared下面新建Error.cshtml
@{
ViewBag.Title = "Error";
}
<div class="text-center">
<h1>Error</h1>
<h2 class="text-red">Error occurred during execution</h2>
<img src="~/error.svg" width="500px" style="margin-top:100px" />
</div>
Program.cs中else里面添加UseExceptionHandler
var app = builder.Build();
app.UseSerilogRequestLogging();
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseExceptionHandlingMiddleware();
}
异常处理中间件ExceptionHandlingMiddleware中添加throw抛出异常,如果不抛出异常就无法定位到Error路由
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);
}
throw;
}
//httpContext.Response.StatusCode = 500;
//await httpContext.Response.WriteAsync("Error occurred");
}
如何根据实际报错显示不同报错内容
改造HomeController
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace CRUDExample.Controllers
{
public class HomeController : Controller
{
[Route("Error")]
public IActionResult Error()
{
IExceptionHandlerPathFeature? exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature != null && exceptionHandlerPathFeature.Error != null)
{
ViewBag.ErrorMessage = exceptionHandlerPathFeature.Error.Message;
}
return View(); //Views/Shared/Error
}
}
}
将ViewBag放到Error.cshtml视图中
@{
ViewBag.Title = "Error";
}
<div class="text-center">
<h1>Error</h1>
<h2 class="text-red">@ViewBag.ErrorMessage</h2>
<img src="~/error.svg" width="500px" style="margin-top:100px" />
</div>
程序运行后显示如下
拓展阅读
Handle errors in ASP.NET Core | Microsoft Learn
Gitee获取源码: