ASP.NET MVC中移除冗餘Response Header

本文主要介紹如何優化ASP.NET MVC使用IIS時Response Header中的不必要的信息


默認的,創建一個ASP.NET MVC項目,會在Response Header中包含一些敏感的信息,這些信息是沒有什麼用處的但是會暴露出IIS的配置信息等。

下面是默認的Response Header信息:

Cache-Control:private, s-maxage=0
Content-Encoding:gzip
Content-Length:8024
Content-Type:text/html; charset=utf-8
Date:Fri, 30 Sep 2016 03:17:10 GMT
Server:Microsoft-IIS/10.0
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.2
X-Frame-Options:SAMEORIGIN
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcV29ya1wyMDE2XE56TmQuSWRlbnRpdHlcR0xELldlYlxTdXBlclxVc2Vycw==?=

 

 

以上內容中,紅色部分並不是必須輸出的信息,相反會暴露服務器的一些配置信息等,以下逐一介紹如何移除不需要的輸出信息:

 

  • X-AspNetMvc-Version

打開Global.asax.cs ,Application_Start方法中,添加如下代碼:

MvcHandler.DisableMvcResponseHeader = true;

 

  • Server

同樣在Global.asax.cs 中,添加如下代碼

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");
    }
}

 

  • X-AspNet-Version

在Web.config文件中找到system.web節點,添加如下配置:

<httpRuntime enableVersionHeader="false" />

 

  • X-Powered-By

在Web.Config文件中找到system.webservice,添加如下配置:

<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

 

OK,做完上面的操作,編譯後打開,F12中可以看到,Response Header內容如下

Cache-Control:private, s-maxage=0
Content-Encoding:gzip
Content-Length:8018
Content-Type:text/html; charset=utf-8
Date:Fri, 30 Sep 2016 02:35:39 GMT
Vary:Accept-Encoding
X-Frame-Options:SAMEORIGIN
X-SourceFiles:=?UTF-8?B?RDpcV29ya1wyMDE2XE56TmQuSWRlbnRpdHlcR0xELldlYlxTdXBlclxVc2Vycw==?=

 

不必要的信息已經被去掉了。清爽很多!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章