在Azure Mobile Serivce .NET后端上启用CORS [英] Enable CORS on Azure Mobile Serivce .NET Backend
问题描述
我修改了ASP.NET Web API 2项目以使用Microsoft Azure Mobile Servies。
我正在开发一个Phonegap应用程序,并使用我的桌面Chrome浏览器和本地运行的Azure Mobile服务进行测试。
在我转换我的项目之前在我的启动代码中使用这行代码处理CORS(需要NuGet包Microsoft.AspNet.WebApi.Cors):
#if DEBUG
var cors = new EnableCorsAttribute(*,*,*);
config.EnableCors(cors);
#if DEBUG
config.MapHttpAttributeRoutes();
...
这个工具就像一个charm,
现在使用Azure Mobile Serives,代码如下所示:
public static void Register()
{
ConfigOptions options = new ConfigOptions();
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
#if DEBUG
var cors = new EnableCorsAttribute(*,*,*);
config.EnableCors(cors);
#endif
}
现在我的CORS设置工作了,没有标题存在。
在web.config中添加标题工作,但我更喜欢编程方法。
< system.webServer>
< httpProtocol>
< customHeaders>
< add name =Access-Control-Allow-Originvalue =*/>
< / customHeaders>
< / httpProtocol>
...
任何想法?
我们会解决这个问题,但这里有一个解决方法:
- 覆盖OnComplete并初始化CORS
- 在调用ServiceConfig.Initialize(...)时,切换到使用新的ConfigBuilder。 )
您可以在这里找到一些示例代码: https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8
希望这有帮助,
Henrik
I modified a ASP.NET Web API 2 project to make use of Microsoft Azure Mobile Servies. I'm developing a Phonegap app and testing it using my Desktop Chrome Browser and a locally running Azure Mobile Service.
Before I "converted" my project I handled CORS using this lines of code in my startup code (requires NuGet Package Microsoft.AspNet.WebApi.Cors):
#if DEBUG
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
#if DEBUG
config.MapHttpAttributeRoutes();
...
This worked like a charm, the required headers for Chrome have been written to the response without a problem.
Now using Azure Mobile Serives, the code looks like this:
public static void Register()
{
ConfigOptions options = new ConfigOptions();
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
#if DEBUG
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
#endif
}
Now my CORS setup does not work anymore, there are no headers present. Adding the header in web.config works, but I would prefer programmatic approach.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
...
Any ideas?
The issue is that CORS uses a special hook in the ASP.NET Web API HttpConfiguration that .NET backend fires a bit too early and so it is not initialized.
We'll fix this, but here is a workaround:
- Create a class that derives from ConfigBuilder
- Override OnComplete and initialize CORS there
- Switch to use your new ConfigBuilder when you call ServiceConfig.Initialize(...)
You can find some sample code here: https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8
Hope this helps,
Henrik
这篇关于在Azure Mobile Serivce .NET后端上启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!