在Azure Mobile Service .NET后端启用CORS

时间:2014-03-26 21:00:07

标签: c# google-chrome cordova cors azure-mobile-services

我修改了一个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>
     ...

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

问题是CORS在ASP.NET Web API HttpConfiguration中使用了一个特殊的钩子,.NET后端过早触发,因此没有初始化。

我们会解决这个问题,但这是一种解决方法:

  1. 创建一个派生自ConfigBuilder的类
  2. 覆盖OnComplete并初始化那里的CORS
  3. 拨打ServiceConfig.Initialize(...)时切换到使用新的ConfigBuilder
  4. 您可以在此处找到一些示例代码:https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8

    希望这有帮助,

    的Henrik