新建一个类HideServerHeaderHelper,继承 IHttpModule,然后重写 OnPreSendRequestHeaders,Dispose,Init方法,如下代码所示
using System; using System.Collections.Generic; using System.Web; namespace MvcApp.Filters { public class HideServerHeaderHelper : IHttpModule { /// <summary> /// List of Headers to remove /// </summary> private readonly List<string> _headersToCloak; /// <summary> /// Initializes a new instance of the <see cref="HideServerHeaderModule"/> class. /// </summary> public HideServerHeaderHelper() { _headersToCloak = new List<string> { "Server", "X-AspNet-Version", "X-AspNetMvc-Version", "X-Powered-By" }; } private void OnPreSendRequestHeaders(object sender, EventArgs e) { //设置Server的值 _headersToCloak.ForEach(h => HttpContext.Current.Response.Headers.Remove(h)); HttpContext.Current.Response.Headers.Set("Server", "nginx"); HttpContext.Current.Response.Headers.Set("Powered-By", "东讯科技有限公司"); } public void Dispose() { _headersToCloak.Clear(); } public void Init(HttpApplication context) { context.PreSendRequestHeaders += OnPreSendRequestHeaders; } } }
在web.config添加以下模块
<system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="HideServerHeaderModule" type="MvcApp.Filters.HideServerHeaderModule"/> </modules> <httpProtocol> <customHeaders> <remove name="Server"/> <remove name="X-AspNet-Version"/> <remove name="X-AspNetMvc-Version"/> <remove name="X-Powered-By"/> </customHeaders> </httpProtocol> </system.webServer>