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

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

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

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

从演练中调整的示例:创建和注册自定义HTTP模块 。 这应该将标头添加到所有.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的模块

        

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

        

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