NetCore實現404和500狀態碼自定義處理頁面

使用NerCore開發框架過程當中須要對404,500等狀態碼進行友好提示頁面處理,參照asp.net mvc並無發現提供Application_Error和Application_BeginRequest方法,是用攔截器路由不匹配的狀況下也不會進行攔截,但NetCore中在Microsoft.AspNetCore.Builder.UseExtensions中提供了Use擴展方法對HttpContext進行了攔截處理,這樣咱們就能夠獲取到Request和Response針對跳轉進行處理,咱們在Startup的Configure方法中加入以下代碼,在404的狀況同時能夠處理訪問項目時的默認路由跳轉,例如訪問http://localhost:4099/fastcloud時不加入具體主頁面路由,則context.Request.Path爲空,能夠跳轉咱們默認制定的主頁mvc

                //自定義404和500處理
                app.Use(async (context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404)
                    {
                        string FilePath = context.Request.Path;
                        if (string.IsNullOrEmpty(FilePath) || FilePath == "/")
                        {
                            context.Request.Path = "/" + AppConfigUtil.Configuration["Frame:DefaultHomeUrl"];
                        }
                        else
                        {
                            context.Request.Path = "/frame/home/error/404";
                        }
                        await next();
                    }
                    if (context.Response.StatusCode == 500)
                    {
                        context.Request.Path = "/frame/home/error/500";
                    }
                });

須要注意的是,若是在項目中加入的全局異常攔截器,則須要判斷若是是頁面請求,纔會跳轉至自定義500頁面,Ajax請求返回錯誤的Json串,具體代碼和效果以下app

    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            string FloderPath = CloudUtil.GetContentPath() + "/Logs";
            DirectoryInfo SystemLogDir = new DirectoryInfo(FloderPath);
            if (!SystemLogDir.Exists)
            {
                SystemLogDir.Create();
            }
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("異常請求url:{0}", context.HttpContext.Request.Path + Environment.NewLine);
            builder.AppendFormat("異常信息:{0}", context.Exception.Message + Environment.NewLine);
            builder.AppendFormat("堆棧信息:{0}", context.Exception.StackTrace + Environment.NewLine);
            LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/Exception", "log_", builder.ToString());
            bool IsAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (IsAjaxCall)
            {
                context.Result = Result.Error("系統發生錯誤,請聯繫管理員!");
                context.ExceptionHandled = true;
            }
            else
            {
                context.Result = new RedirectResult(CloudUtil.GetRootPath() + "frame/home/error/500");
                context.ExceptionHandled = true;
            }

        }

相關文章
相關標籤/搜索