Asp.Net Core 404处理 Asp.Net Core异常处理整理

在使用Asp.Net Core Mvc时 404处理整理如下

一、自带404状态处理

1.控制器视图子弹404视图 NotFoundResult,NotFoundObjectResult

        //
        // 摘要:
        //     Creates an Microsoft.AspNetCore.Mvc.NotFoundObjectResult that produces a Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound
        //     response.
        //
        // 返回结果:
        //     The created Microsoft.AspNetCore.Mvc.NotFoundObjectResult for the response.
        [NonAction]
        public virtual NotFoundObjectResult NotFound(object value);
        //
        // 摘要:
        //     Creates an Microsoft.AspNetCore.Mvc.NotFoundResult that produces a Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound
        //     response.
        //
        // 返回结果:
        //     The created Microsoft.AspNetCore.Mvc.NotFoundResult for the response.
        [NonAction]
        public virtual NotFoundResult NotFound();

2.当前操作返回404状态,或者返回404的一句话提示。

二、自定义404页面显示

在网站中,为了增强提前,通常使用自定义404页面

1.自定义404视图,在控制器中返回

    /// <summary>
    /// 定义404视图
    /// </summary>
    public class NotFoundViewResult : ViewResult
    {
        public NotFoundViewResult(string viewName)
        {
            ViewName = viewName;
            StatusCode = (int)HttpStatusCode.NotFound;
        }
    }

2.在控制器中返回使用

        public IActionResult Index()
        {
            //返回404页面
            return new NotFoundViewResult("~/views/Error/code_404.cshtml");

            return View();
        }

3.呈现结果:

三、更多错误处理

更多:

Asp.Net Core异常处理整理

.Net Core邮件发送之MailKit

Asp.Net Core中Json序列化处理整理

猜你喜欢

转载自www.cnblogs.com/tianma3798/p/10122910.html