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

 

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            
            app.UseStatusCodePagesWithReExecute("/Home/ErrorStatusCode", "?statusCode={0}");

 

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

 

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

 

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

 

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

 

@model ErrorViewModel

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<p>Status: @ViewData["StatusCode"]</p>
@if (Model.ShowRequestId)
{
    <p>
        <strong>Request ID:</strong> <code>@Model.RequestId</code>
    </p>
}

<h3>Development Mode</h3>
<p>
    Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
    <strong>The Development environment shouldn't be enabled for deployed applications.</strong>
    It can result in displaying sensitive information from exceptions to end users.
    For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
    and restarting the app.
</p>

 

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

 

效果预览

 

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

分类: 电脑数码 标签: asp.net c# 发布于: 2020-12-26 19:18:18, 点击数: