Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove headers from my Web API response? [duplicate]

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.

like image 710
DenaliHardtail Avatar asked Aug 21 '14 20:08

DenaliHardtail


3 Answers

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");
        }
    }
}
like image 115
Tushar Kesare Avatar answered Oct 01 '22 00:10

Tushar Kesare


Solution-1

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>

Solution-2

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");
}
like image 41
Emdadul Sawon Avatar answered Oct 01 '22 01:10

Emdadul Sawon


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);
like image 20
Ger Groot Avatar answered Oct 01 '22 01:10

Ger Groot