WebAPI CORS和静态文件 [英] WebAPI CORS and static files
问题描述
我有一个WebApi,它启用了CORS,并且运行良好。
我想添加由API提供的静态文件,以补充实际文件。 WebAPI方法。
如果直接访问静态文件,则可以很好地提供它们,但是,如果我尝试将它们ajax到另一个域中,则会出现CORS问题。 / p>
有问题的实际文件是静态.html文件。
我真的不想创建包装器控制器提供静态文件,因为如果我动态执行它会带来很多安全问题。
我目前正在使用自定义的进行CORS DelegatingHandler
(不是WebAPI2的内置方式),但是没有为静态文件调用此处理程序。
如何拦截静态文件
假设您正在使用 IAppBuilder.UseFileServer(...)
与 FileServerOptions
提供静态文件,您可以在其中添加CORS标头。
var options = new FileServerOptions
{
...
StaticFileOptions =
{
OnPrepareResponse = AddCorsHeader
},
...
};
您的处理程序可以是(例如):
私有静态无效AddCorsHeader(StaticFileResponseContext obj)
{
obj.OwinContext.Response.Headers [ Access-Control-Allow-Origin] = *;
}
它的范围很广,但对我来说很好。
I have a WebApi, it is CORS enabled and works nicely.
I want to add static files which are served up by the API to be supplementary to the actual WebAPI methods.
The static files are served up just fine if you go to them directly, however if I try and ajax them in on another domain I get CORS issues.
The actual file in question is a static .html file.
I really don't want to create a wrapper controller to serve up static files as it opens a bunch of security concerns if I do it dynamically.
I am currently doing CORS with a custom DelegatingHandler
(not the WebAPI2 builtin way) but this handler is not getting called for static files.
How can I intercept static file requests in WebAPI and apply the relevent CORS headers where applicable?
Assuming you're using IAppBuilder.UseFileServer(...)
with FileServerOptions
to serve your static files, you can add the CORS headers there.
var options = new FileServerOptions
{
...
StaticFileOptions =
{
OnPrepareResponse = AddCorsHeader
},
...
};
And your handler can just be (for example):
private static void AddCorsHeader(StaticFileResponseContext obj)
{
obj.OwinContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
}
It's pretty broad but works just fine for me.
这篇关于WebAPI CORS和静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!