问题
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:
- Create a class that derives from ConfigBuilder
- Override OnComplete and initialize CORS there
- 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