C# 移除Response Header,403调整返回为404Make IIS return a 404 status code instead of 403

时间:2023-03-09 03:45:10
C# 移除Response Header,403调整返回为404Make IIS return a 404 status code instead of 403

Server Information Revealed

For the benefit of those who land here through a google/bing search:: Here's the summary of steps:

Step 1: Create a class that derives from IHttpModule (and IDisposable to clean up when we're done):

public class MyCustomModule : IHttpModule, IDisposable
{
private HttpApplication _httpApplication;
private static readonly List<string> HeadersToCloak = new List<string>
{
"Server",
"X-AspNet-Version",
"X-AspNetMvc-Version",
"X-Powered-By"
};
}

Step 2: Get a reference to the intrinsic context in the IHttpModule.Init method, and assign an event handler to the PreSendRequestHeaders event:

public void Init(HttpApplication context)
{
_httpApplication = context; context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}

Step 3: Now the headers can be removed like so:

private void OnPreSendRequestHeaders(object sender, EventArgs e)
{
if (null == _httpApplication)
{
return;
} if (_httpApplication.Context != null)
{
var response = _httpApplication.Response;
HeadersToCloak.ForEach(header => response.Headers.Remove(header));
}
}

Step 4: Now register this module in your root web.config under the system.webserver (if running IIS 7.0 integrated mode more details here):

<configuration>
<system.webServer>
<modules>
<add name="MyCustomModule" type="<namespace>.MyCustomModule "/>
</modules>
</system.webServer>
</configuration>

Hidden Directories Detected On Server

Another way is to create a handler in your web.config file that will return the 404 status code.

namespace MyNameSpace
{
public class NoAccessHandler: IHttpHandler
{ #region IHttpHandler Members public bool IsReusable
{
get { return true; }
} public void ProcessRequest(HttpContext context)
{
context.Response.StatusCode = 404;
} #endregion
}
}

in your web.config:

<httpHandlers>
<add verb="*" path="docs/*" validate="false" type="MyNameSpace.NoAccessHandler"/>
</httpHandlers> <system.webServer>
<handlers>
<add name="NoAccess" verb="*" path="docs/*" preCondition="integratedMode" type="MyNameSpace.NoAccessHandler"/>
</handlers>
</system.webServer>