Pregunta

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.

¿Fue útil?

Solución

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).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top