站点的Headers里面会暴露一些服务器的环境,例如IIS版本、语言的环境等
有时候我们不想让用户了解这类信息那么可以这样做:
1、修改web.config
在 <system.webServer> 节点里加上隐藏掉 X-Powered-By
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<remove name="Server" />
</customHeaders>
</httpProtocol>
2、增加一个 HttpHeadersCleanup 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyNameSpace
{
/// <summary>
/// Removing HTTP Headers for ASP.NET sites
/// </summary>
public class HttpHeadersCleanup : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders += PreSendRequestHeaders;
}
private static void PreSendRequestHeaders(object sender, EventArgs e)
{
try
{
HttpApplication app = sender as HttpApplication;
var headers = app.Context.Response.Headers;
if (null != headers)
{
headers.Remove("Server");
}
}
catch { }
}
public void Dispose()
{
}
}
}
3、再次修改web.config
在 <system.webServer> 节点下增加:
<!--Removing HTTP Headers for ASP.NET sites-->
<modules runAllManagedModulesForAllRequests="true">
<add name="HttpHeadersCleanup " type="MyNameSpace.HttpHeadersCleanup"/>
</modules>
修改完成的 <system.webServer> 节点:
<system.webServer>
<!--Removing HTTP Headers for ASP.NET sites-->
<modules runAllManagedModulesForAllRequests="true">
<add name="HttpHeadersCleanup " type="MyNameSpace.HttpHeadersCleanup"/>
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
......
</system.webServer>
发布后再看HTTP Headers简洁多了: