为ASP.NET MVC中的静态资源启用CORS?

时间:2014-03-26 20:38:39

标签: c# ajax asp.net-mvc cors

我在Web API和ASP .NET MVC中的通用控制器中找到了大量有关CORS的资源。

但是,我的情况是,我希望特定文件夹中的所有静态资源(CSS和JS文件)也可以通过AJAX下载。换句话说,为这些资源或该文件夹启用CORS。

我怎样才能做到这一点?我没有发现类似的问题。它们都与Web API或通用控制器有关。

1 个答案:

答案 0 :(得分:6)

改编自Walkthrough: Creating and Registering a Custom HTTP Module的示例。这应该将标头添加到所有.js.css请求。

创建模块

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() { }
}

注册以经典模式运行的IIS 6.0和IIS 7.0的模块

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

注册在集成模式下运行的IIS 7.0模块

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

当您运行MVC时,请确保更改根目录中的那个(而不是Views文件夹)。

相关问题