Removing headers from the response

前端 未结 4 1132
予麋鹿
予麋鹿 2021-01-11 11:52

I need to cloak certain headers generated by ASP.NET and IIS and returned in the responses from a ASP.NET WebAPI service. The headers I need to cloak are:

  • Serv
4条回答
  •  甜味超标
    2021-01-11 12:21

    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 HeadersToCloak = new List
                {
                    "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):

    
      
        
          
        
      
    
    

    Hope this helps!

提交回复
热议问题