Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable CORS for static resources in ASP .NET MVC?

I've found plenty of resources regarding CORS in Web APIs and for general controllers in ASP .NET MVC.

However, I'm in a situation where I'd like all static resources (CSS and JS files) inside a specific folder to be downloadable through AJAX as well. In other words, enable CORS for those resources or that folder.

How can I accomplish this? I've found no similar question. They are all related to web APIs or general controllers.

like image 379
Mathias Lykkegaard Lorenzen Avatar asked Mar 26 '14 20:03

Mathias Lykkegaard Lorenzen


People also ask

How do I enable CORS in C#?

First, we need to enable CORS in WebAPI, then we call the service from other application AJAX request. In order to enable CORS, we need to install the JSONP package from NuGet (see Figure3). After adding Jsonp package, we need to add the following code-snippet in App_Start\WebApiConfig. cs file.


1 Answers

Example adapted from Walkthrough: Creating and Registering a Custom HTTP Module. This should add the header to 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 the 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 the module for IIS 7.0 running in Integrated mode

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

As you are running MVC, make sure you alter the one in the root (not the Views folder).

like image 98
SilverlightFox Avatar answered Nov 09 '22 21:11

SilverlightFox