1. 程式人生 > >Asp.Net Core 404處理 Asp.Net Core異常處理整理

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序列化處理整理