簡體   English   中英

如何在ASP.NET MVC中隱藏服務器版本以解決自定義錯誤?

[英]How to hide server version for custom errors in asp.net mvc?

錯誤頁面顯示IIS服務器版本 嗨,我正在開發.net mvc中的Web應用程序。 我在customheaders中使用<remove name="X-Powered-By" />隱藏服務器版本。 它工作正常,我能夠隱藏iis版本。 這僅適用於存在的頁面。 我也實現了

 <customErrors defaultRedirect="Errorpage.html" mode="On">
      <error statusCode="500" redirect="~/Login/Index" />
      <error statusCode="400" redirect="~/Login/Index" />
    </customErrors>

自定義錯誤。 例如,如果我嘗試訪問不存在的頁面,那么我將被重定向到Errorpage.html,但是在這種情況下,用戶可以看到服務器版本。

以下是我的global.asax代碼。

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            MvcHandler.DisableMvcResponseHeader = true;

        }
        protected void Application_PreSendRequestHeaders()
        {
            Response.Headers.Remove("Server");
            Response.Headers.Set("Server", "");
            Response.Headers.Remove("X-AspNet-Version"); //alternative to above solution
            Response.Headers.Remove("X-AspNetMvc-Version"); //alternative to above solution
        }

新的自定義錯誤 我可以知道在存在的頁面和不存在的頁面中如何解決此問題! 我可以得到一些幫助來解決這個問題嗎? 任何幫助將不勝感激。 謝謝。

您可以為404創建一個自定義錯誤頁面,並將其添加到您的web.config文件中。

<error statusCode="404" redirect="~/Home/PageNotFound" />

其中,PageNotFound是您在HomeController中返回視圖的操作。

現在,將您的Global.asax.cs文件打開到Application_Start,並在頂部添加以下代碼:

MvcHandler.DisableMvcResponseHeader = true;

您可以通過向PreSendRequestHeaders事件添加處理程序來消除“ Server”標頭,如下所示:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    HttpApplication app = sender as HttpApplication;
    if (app != null &&
        app.Context != null)
    {
        app.Context.Response.Headers.Remove("Server");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM