启用ASP .NET MVC的静态资源CORS? [英] Enable CORS for static resources in ASP .NET MVC?
问题描述
我已经找到了很多关于网络的API以及在ASP .NET MVC一般控制器CORS的资源。
I've found plenty of resources regarding CORS in Web APIs and for general controllers in ASP .NET MVC.
不过,我在一个情况下我倒是像一个特定的文件夹内的所有静态资源(CSS和JS文件),并通过AJAX可下载为好。换句话说,能够对这些资源或文件夹CORS。
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.
我怎样才能做到这一点?我没有发现类似的问题。他们都涉及到网络的API或通用控制器
How can I accomplish this? I've found no similar question. They are all related to web APIs or general controllers.
推荐答案
实例改编而成的演练:创建和注册自定义HTTP模块。这应该添加标题,所有的的.js
和的.css
请求。
Example adapted from Walkthrough: Creating and Registering a Custom HTTP Module. This should add the header to all .js
and .css
requests.
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在经典模式下运行
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>
要注册为IIS 7.0模块中集成模式下运行
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>
当你正在运行的MVC,确保你改变了一个在根(而不是查看
文件夹)。
这篇关于启用ASP .NET MVC的静态资源CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!