1. 程式人生 > >學習Net Core 2.0 做博客 錯誤頁中間件

學習Net Core 2.0 做博客 錯誤頁中間件

int ask nbu thrown () final response gate execute

CustomErrorPagesMiddleware

public class CustomErrorPagesMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly Microsoft.Extensions.Logging.ILogger _logger;
        private readonly IHostingEnvironment _env;
        public CustomErrorPagesMiddleware(
            RequestDelegate next,
            ILoggerFactory loggerFactory,
            IHostingEnvironment env)
        {
            _next 
= next; _logger = loggerFactory.CreateLogger<CustomErrorPagesMiddleware>(); _env = env; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(
0, ex, "An unhandled exception has occurred while executing the request"); if (context.Response.HasStarted) { _logger.LogWarning("The response has already started, the error page middleware will not be executed."); throw; }
try { context.Response.Clear(); context.Response.StatusCode = 500; return; } catch (Exception ex2) { _logger.LogError(0, ex2, "An exception was thrown attempting to display the error page."); } throw; } finally { var statusCode = context.Response.StatusCode; if (statusCode == 404 || statusCode == 500|| statusCode == 403) { await ErrorPage.ResponseAsync(context.Response, statusCode,_env); } } } }

ErrorPage

 public static class ErrorPage
    {
        public static async Task ResponseAsync(HttpResponse response, int statusCode, IHostingEnvironment env)
        {
            if (statusCode == 404)
            {
                 
                 await response.WriteAsync(Page404,Encoding.UTF8);
           
            }
            else if (statusCode == 500)
            {
                await response.WriteAsync(Page500);
            }else if (statusCode == 403)
            {
              //沒有權限服務器會返回403;
                await response.WriteAsync(Page403);
            }
        }

        private static string Page404 => "404";

        private static string Page500 => "500";

        private static string Page403 => "403";
    }

CustomErrorPagesExtensions

 public static class CustomErrorPagesExtensions
    {
        public static IApplicationBuilder UseCustomErrorPages(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return app.UseMiddleware<CustomErrorPagesMiddleware>();
        }
    }

Startup

 app.UseCustomErrorPages();

學習Net Core 2.0 做博客 錯誤頁中間件