asp.net core使用中間件美化開發環境異常頁面

asp.net core系統自帶的異常頁面色彩給人感受模糊、朦朧,暈眩!css

 

原版:git

 

美化版github

 

 

實現思路:(在系統自帶異常中間件「DeveloperExceptionPageMiddleware」執行後,調用自定義的異常中間件「DeveloperExceptionPrettifyMiddleware」,繼續向響應流輸出美化的css和js)asp.net

/// <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();
            }
        }
    }
}

 

使用中間件(注意順序)async

源碼下載spa

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

相關文章
相關標籤/搜索