Mat*_*zen 6 c# ajax 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() { }
}
Run Code Online (Sandbox Code Playgroud)
<configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</httpModules>
</system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)
在运行MVC时,请确保更改根目录(而不是Views文件夹)中的那个.
| 归档时间: |
|
| 查看次数: |
5721 次 |
| 最近记录: |