简体   繁体   English

在Azure Mobile Serivce .NET后端启用CORS

[英]Enable CORS on Azure Mobile Serivce .NET Backend

I modified a ASP.NET Web API 2 project to make use of Microsoft Azure Mobile Servies. 我修改了一个ASP.NET Web API 2项目以使用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. 我正在开发一个Phonegap应用程序并使用我的桌面Chrome浏览器和本地运行的Azure移动服务对其进行测试。

Before I "converted" my project I handled CORS using this lines of code in my startup code (requires NuGet Package Microsoft.AspNet.WebApi.Cors): 在我“转换”我的项目之前,我在我的启动代码中使用这行代码处理CORS(需要NuGet包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. 这就像一个魅力,Chrome的必需标题已写入响应没有问题。

Now using Azure Mobile Serives, the code looks like this: 现在使用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
}

Now my CORS setup does not work anymore, there are no headers present. 现在我的CORS设置不再起作用,没有标题存在。 Adding the header in web.config works, but I would prefer programmatic approach. 在web.config中添加标题有效,但我更喜欢编程方法。

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

We'll fix this, but here is a workaround: 我们会解决这个问题,但这是一个解决方法:

  1. Create a class that derives from ConfigBuilder 创建一个派生自ConfigBuilder的类
  2. Override OnComplete and initialize CORS there 覆盖OnComplete并在那里初始化CORS
  3. Switch to use your new ConfigBuilder when you call ServiceConfig.Initialize(...) 当您调用ServiceConfig.Initialize(...)时切换到使用新的ConfigBuilder

You can find some sample code here: https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8 你可以在这里找到一些示例代码: https//gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8

Hope this helps, 希望这可以帮助,

Henrik 亨里克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM