.net core 自定义404 500页面

常用处理方式

自己定制网站的404、500页面的方式有很多,比如修改nginx配置文件,指定请求返回码对应的页面,
.netframework项目中修改webconfig文件,指定customerror节点的文件路径都可以。
在那么在.net core中如何处理呢。

500错误页

  • 500的错误都是靠拦截处理,在.netcore mvc拦截器中处理也可以。
public class ErrorPageFilter : ActionFilterAttribute
{
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            if (context.HttpContext.Response.StatusCode == 500)
            {
                context.HttpContext.Response.Redirect("error/500");
            }
            base.OnResultExecuted(context);
        }
}

[ErrorPageFilter]
public abstract class PageController
{}
  • .net core mvc 创建的时候也自带了错误页的管道处理
    在 startup.cs中
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
            //开发环境直接展示错误堆栈的页面
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //正式环境自定义错误页
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
}

在 home控制器中 有这样的方法
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

自己把 error视图文件替换掉自己想要的样式就可以了。

404页面

通过上述方法是拦截不到404页面的,应该借助管道的中间件去处理,在 startup.cs文件的 configure方法中添加

  app.UseStatusCodePagesWithReExecute("/error/{0}");

添加 error控制器

public class ErrorController : Controller
{
        /// <summary>
        /// {0}中是错误码
        /// </summary>
        /// <returns></returns>
        [Route("/error/{0}")]
        public IActionResult Page()
        {
            //跳转到404错误页
            if (Response.StatusCode == 404)
            {
                return View("/views/error/notfound.cshtml");
            }
            return View();
        }
}

需要注意的是错误页拦截不要写在这里在上面的 app.UseExceptionHandler("/Home/Error"); 控制器中处理就行了

posted @ 2019-05-21 11:16  sands  阅读(1518)  评论(0编辑  收藏  举报