Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top