asp.net core 自定义错误页面

简介

这篇文章教学如何在asp.net core项目下面,自定义错误页面,处理404,403等错误页面。


官方文档


https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1


实战操作


在项目Startup.cs 中 Configure中增加app.UseStatusCodePagesWithReExecute


<code>     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

app.UseStatusCodePagesWithReExecute("/Home/ErrorStatusCode", "?statusCode={0}");/<code>


这个api,作用是把Exception,转交给特定的控制器执行,我们例子里,是给/Home 控制器下面的ErrorStatusCode方法处理。 后面第二个参数,是传递错误码


我们看看具体的方法里面怎么处理,方法有一个参数int statusCode接收传过来的错误码参数,然后赋值到ViewData里面,以备后面模板视图来渲染。


<code>        public IActionResult ErrorStatusCode(int statusCode = 0)
{
ViewData["Title"] = "出错啦";
ViewData["StatusCode"] = statusCode;
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
/<code>


然后创建一个模板位于:Views/Shared/ErrorStatusCode.cshtml


<code>@model ErrorViewModel

Error.


An error occurred while processing your request.


Status: @ViewData["StatusCode"]


@if (Model.ShowRequestId)
{


Request ID: <code>@Model.RequestId/<code>


}

Development Mode



Swapping to Development

environment will display more detailed information about the error that occurred.



The Development environment shouldn't be enabled for deployed applications.
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development
and restarting the app.

/<code>


模板中显示Status: @ViewData["statusCode"]


效果预览


访问一个不存在的页面,就可以看到404错误页面,效果如下


asp.net core 自定义错误页面


分享到:


相關文章: