Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Programmatically set HTTP headers on static content

I have an ASP.NET application with a filter wired up in RegisterGlobalFilters that performs the following:

public class XFrameOptionsAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.AddHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
    }
}

Looking in Fiddler, I can see that views returned from the webserver include this header. Static files however, such as JavaScript do not include this header in the HTTP response.

How do I get ASP.NET MVC to also apply this filter to any static files the web server returns?

like image 565
codechurn Avatar asked Jan 22 '16 17:01

codechurn


2 Answers

One way to set headers for all the content of site is in web.config. The customHeaders section will make sure that this header is included for all files and responses.

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-FRAME-OPTIONS" value="SAMEORIGIN" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Another option is to create custom HttpModule as shown below. This way you have more control on the files and content to which headers needs to be appended.

namespace MvcApplication1.Modules
{
    public class CustomOriginHeader : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose() { }

        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            // For example - To add header only for JS files
            if (HttpContext.Current.Request.Url.ToString().Contains(".js"))
            {
                HttpContext.Current.Response.Headers.Add("X-FRAME-OPTIONS", "SAMEORIGIN");
            }
        }
    }
}

And then register them in web.config as shown below -

  <system.webServer>
     <modules>
        <add name="CustomHeaderModule" type="MvcApplication1.Modules.CustomOriginHeader" />
     </modules>
  </system.webServer>
like image 78
ramiramilu Avatar answered Nov 20 '22 18:11

ramiramilu


This is something that if you want on every request (static or dynamic requests), you should probably set it up through IIS (the web server). Here are some details on different ways that you can achieve this - http://www.iis.net/configreference/system.webserver/httpprotocol/customheaders

In short, you could do this in your web.config file

<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-Custom-Name" value="MyCustomValue" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

If you have access directly to IIS, you can use the UI to set this up as well.

like image 5
Tommy Avatar answered Nov 20 '22 19:11

Tommy