我修改了一个ASP.NET Web API 2项目以使用Microsoft Azure Mobile Servies。 我正在开发一个Phonegap应用,并使用我的桌面Chrome浏览器和本地运行的Azure移动服务进行测试。
在我"转换之前#34;我的项目我在启动代码中使用这行代码处理CORS(需要NuGet包Microsoft.AspNet.WebApi.Cors):
#if DEBUG
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
#if DEBUG
config.MapHttpAttributeRoutes();
...
这就像一个魅力,Chrome的所需标题已经写入响应没有问题。
现在使用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-Origin" value="*" />
</customHeaders>
</httpProtocol>
...
有什么想法吗?
答案 0 :(得分:3)
问题是CORS在ASP.NET Web API HttpConfiguration中使用了一个特殊的钩子,.NET后端过早触发,因此没有初始化。
我们会解决这个问题,但这是一种解决方法:
您可以在此处找到一些示例代码:https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8
希望这有帮助,
的Henrik