New Web API 2.0 project so we have full control over the entire request / response pipeline.
How do we remove the "X-" headers from a response sent by ASP.NET Web API response? Specifically, at the moment and always subject to change, we want to remove "X-AspNet-Version
", "X-Powered-By
", and "X-SourceFiles
".
We tried result.Headers.Remove("X-AspNet-Version");
before returning the HttpResponseMessage
from the controller. That didn't work as the headers still appeared in Fiddler. I also didn't find any headers anywhere on the HttpResponseMessage
object. To me, this indicated I may need to dig deeper into the pipeline but I'm not sure where to start or if that's correct.
Alternative solution I implemented is to define your own Http module and remove headers in OnPreSendRequestHeaders handler. This removes headers from all ASP.NET and Web API requests as well as static content requests. And you can reuse it in multiple projects.
public class RemoveHttpHeadersModule : IHttpModule
{
public void Init(HttpApplication context)
{
Guard.ArgumentNotNull(context, "context");
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
public void Dispose() { }
void OnPreSendRequestHeaders(object sender, EventArgs e)
{
var application = sender as HttpApplication;
if (application != null)
{
HttpResponse response = application.Response;
response.Headers.Remove("Server");
response.Headers.Remove("X-Powered-By");
}
}
}
From this answer
The "powered by" is a custom header in IIS. Changing it depends on the version of IIS you are using. For some information on how to modify or remove, see here:
To remove the MVC header, In Global.asax, in the Application Start event:
MvcHandler.DisableMvcResponseHeader = true;
Put this in the web.config get rid of the X-AspNet-Version header:
<system.web>
<httpRuntime enableVersionHeader="false" />
</system.web>
You can change any header or anything in Application_EndRequest()
try this
protected void Application_EndRequest()
{
// removing excessive headers. They don't need to see this.
Response.Headers.Remove("header_name");
}
If you are using Owin, you can add this to your startup class to remove the 'Server' header.
app.Use((context, next) =>
{
context.Response.Headers.Remove("Server");
return next.Invoke();
});
app.UseStageMarker(PipelineStage.PostAcquireState);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With