asp.net core使用中间件美化开发环境异常页面

asp.net core系统自带的异常页面色彩给人感觉模糊、朦胧,晕眩!

 

原版:

 

美化版

 

 

实现思路:(在系统自带异常中间件“DeveloperExceptionPageMiddleware”执行后,调用自定义的异常中间件“DeveloperExceptionPrettifyMiddleware”,继续向响应流输出美化的css和js)

/// <summary>
/// 开发环境异常页面css美化 中间件
/// </summary>
public class DeveloperExceptionPrettifyMiddleware
{
    private readonly RequestDelegate _next;

    public DeveloperExceptionPrettifyMiddleware(
        RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await _next.Invoke(context);

        if (context.Response.StatusCode == 500) // 通过 StatusCode 判断程序报错
        {
            using (TextWriter output = (TextWriter)new StreamWriter(context.Response.Body,
                new UTF8Encoding(false, true), 4096, true))
            {
                // 美化版 css/js
                var chars = @"
                    <style>
                        body{ color: inherit}
                        h1{color:red}
                        h3{color:inherit}
                        .titleerror{color:maroon}
                        body .location{ }
                        #header li{color:blue}
                        #header .selected{background:#44525e}
                        #stackpage .source ol li{background-color:#ffffcc}
                        #stackpage .source ol.collapsible li span{color:#000}
                        .rawExceptionStackTrace{background-color:#ffffcc; padding:.5rem}
                        :focus{outline:none}
                        .showRawException{color:blue}
                    </style>
                    <script>
                        document.querySelector('.expandCollapseButton').click()
                    </script>
            ".ToCharArray();

                // 输出到响应流中
                await output.WriteAsync(chars, 0, chars.Length);
                await output.FlushAsync();
            }
        }
    }
}

 

使用中间件(注意顺序)

源码下载

https://github.com/246850/AspNetCore.Prettify/

 

posted @ 2019-06-18 15:13  神叉  阅读(744)  评论(2编辑  收藏  举报