Enable CORS on Azure Mobile Serivce .NET Backend

耗尽温柔 提交于 2019-12-11 12:54:10

问题


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?


回答1:


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:

  1. Create a class that derives from ConfigBuilder
  2. Override OnComplete and initialize CORS there
  3. 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



来源:https://stackoverflow.com/questions/22672941/enable-cors-on-azure-mobile-serivce-net-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!