How to remove ASP.Net MVC Default HTTP Headers?

前端 未结 11 2222
自闭症患者
自闭症患者 2020-11-28 01:23

Each page in an MVC application I\'m working with sets these HTTP headers in responses:

X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
X-AspNetMvc-Version         


        
11条回答
  •  悲哀的现实
    2020-11-28 01:55

    .NET Core

    To remove the Server header, within the Program.cs file, add the following option:

    .UseKestrel(opt => opt.AddServerHeader = false)
    

    For dot net core 1, put add the option inside the .UseKestrel() call. For dot net core 2, add the line after UseStartup().

    To remove X-Powered-By header, if deployed to IIS, edit your web.config and add the following section inside the system.webServer tag:

    
        
            
        
    
    

    .NET 4.5.2

    To remove the Server header, within your global.asax file add the following:

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string[] headers = { "Server", "X-AspNet-Version" };
    
            if (!Response.HeadersWritten)
            {
                Response.AddOnSendingHeaders((c) =>
                {
                    if (c != null && c.Response != null && c.Response.Headers != null)
                    {
                        foreach (string header in headers)
                        {
                            if (c.Response.Headers[header] != null)
                            {
                                c.Response.Headers.Remove(header);
                            }
                        }
                    }
                });
            }
    
        }
    

    Pre .NET 4.5.2

    Add the following c# class to your project:

    public class RemoveServerHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }
    
        public void Dispose() { }
    
        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Remove("Server");
        }
    }
    

    and then within your web.config add the following section:

    
        ....
     
        
     
    

    However I had a problem where sub-projects couldn't find this module. Not fun.

    Removing X-AspNetMvc-Version header

    To remove the ''X-AspNetMvc-Version'' tag, for any version of .NET, modify your ''web.config'' file to include:

    
    ...
       
    ...
    
    

    Thanks Microsoft for making this unbelievably difficult. Or maybe that was your intention so that you could track IIS and MVC installs across the world ...

提交回复
热议问题