Enable CORS for static resources in ASP.NET MVC?

I found a lot of resources regarding CORS in web APIs and general controllers in ASP.NET MVC.

However, I am in a situation where I would like all static resources (CSS and JS files) inside a specific folder to be loaded via AJAX. In other words, enable CORS for these resources or this folder.

How can i do this? I did not find a similar question. All are associated with web APIs or controllers.

+5
c # ajax asp.net-mvc cors
Mar 26 '14 at 20:38
source share
1 answer

Example adapted from Walkthrough. Create and register a custom HTTP module . This should add a header for all .js and .css requests.

Create module

 using System; using System.Web; public class HelloWorldModule : IHttpModule { public HelloWorldModule() { } public String ModuleName { get { return "HelloWorldModule"; } } // In the Init function, register for HttpApplication // events by adding your handlers. public void Init(HttpApplication application) { application.BeginRequest += (new EventHandler(this.Application_BeginRequest)); } private void Application_BeginRequest(Object source, EventArgs e) { // Create HttpApplication and HttpContext objects to access // request and response properties. HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; string filePath = context.Request.FilePath; string fileExtension = VirtualPathUtility.GetExtension(filePath); if (fileExtension.Equals(".css") || fileExtension.Equals(".js")) { context.Response.AddHeader("Access-Control-Allow-Origin", "*"); } } public void Dispose() { } } 

To register a module for IIS 6.0 and IIS 7.0 running in classic mode

 <configuration> <system.web> <httpModules> <add name="HelloWorldModule" type="HelloWorldModule"/> </httpModules> </system.web> </configuration> 

To register a module for IIS 7.0 running in integrated mode

 <configuration> <system.webServer> <modules> <add name="HelloWorldModule" type="HelloWorldModule"/> </modules> </system.webServer> </configuration> 

When you use MVC, make sure you change it in the root folder (and not in the Views folder).

+5
Apr 03 '14 at 17:35
source share



All Articles