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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM