Enable CORS in Azure web

白昼怎懂夜的黑 提交于 2020-01-23 03:24:47

问题


What I´m trying to do is to enable CORS (Cross-origin Resource Sharing) for .net MVC 5 Azure website when calling a https service (not my own) from my JavaScript.

I always get the same error

XMLHttpRequest cannot load https://someservice-I-have-no-control-over. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://my.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 400.

I have managed to enable this when developing locally, setting my project to https and adding the following to web.config

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, SOAPAction"/>
    <add name="Access-Control-Max-Age" value="1728000"/>
  </customHeaders>
</httpProtocol>
</system.webServer>

That adds the 'Access-Control-Allow-Origin' header. But that does not seem to work on the Azure website.

And I can´t find any settings like in the Mobile Services where you can allow this like you see here.

Since I know you are all going to ask for code (that works locally btw) there you have the simple Jquery call to the service

$.ajax({
    url: 'https://someservice-I-have-no-control-over',
    dataType: 'json',
    contentType: 'application/json',
    type: 'GET',
    success: function (response) {
        $.each(response, function (key, value) {
          console.log("success"); //Doesn´t happen! :-(
        });
    },
    error: function (xhr, text, error) {
        if ($.isFunction(onError)) {
            onError(xhr.responseJSON);
        }
    }
});

So any thoughts?

Edit 1

Just to clarify a little.

I am calling a service that I have no control over that is a https one, in a javascript (not a controller) that is mine.

Edit 2

Ok I thought that I could intercept the response from the third party service and add this header before the browser rejects it. As I see it that is not possible (right?). But how come it works locally?

If I capture the call to this service with e.g LiveHTTPHeaders I get the following response where there is not a "Access-Control-Allow-Origin" restriction (so way does it work locally?).

Request (to https://someservice-I-have-no-control-over.com)

GET /someservice-I-have-no-control-over/SomeAction/44 HTTP/1.1
Host: someservice-I-have-no-control-over.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-None-Match: "53867cff-96b0-411f-88b7-d84765f9f8e8"
Cache-Control: max-age=0

Reply

HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Date: Tue, 24 Feb 2015 11:06:53 GMT

回答1:


Not possible.

It works locally because it's the server that must have the allow headers, and when you call your own webserver from your javascript you can add those headers.

When you call the real website they do probably not add the CORS allow header (Access-Control-Allow-Origin) and your request is therefore denied.

What you could do is either to use JSONP or proxy all requests through your own website.

You could for instance use my CORS proxy: https://github.com/jgauffin/corsproxy. It's intended usage is for IE9 and below, but works just as fine for all requests.




回答2:


WebApiConfig I set it the WebApiConfig class and it worked. I also had issues on Azurewebsites when trying to set it via web.config.

Try this in WebApiConfig:

   var cors = new EnableCorsAttribute("*", "*", "*");

   config.EnableCors(cors);

You can edit the "", "", "*" if you don't want to allow everything.




回答3:


If you're using Owin, you can do this in the Startup.cs file:

app.UseCors(CorsOptions.AllowAll);

Use this if and only if you intentionally plan to expose your API to all origins and headers.

Else, you can try it this way by decorating your controller or specific methods:

 [EnableCors(origins: "http://someCallingService", headers: "*", methods: "*")]

Check out THIS article




回答4:


I addressed this by installing the following package:

Microsoft.AspNet.WebApi.Cors

...then using the Config.EnableCors() as described above and altering my web.config transform:

In WebApiConfig.cs:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Continue configuration as you wish... 
    }

Then, in the web.config transform, in my case named web.PPE.config because it's for Pre-Production:

<system.webServer>
    <httpProtocol>
        <!-- custom headers necessary for CORS -->
        <customHeaders xdt:Transform="Replace">
        <clear /> <!-- the clear here is important! -->
        <add name="Access-Control-Allow-Origin" value="http://url-that-is-allowed-to-communicate-with-this-server.com" />
        <!-- must match server DNS address or SignalR can't communicate with Hub remotely -->
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

YMMV on whether to include the Allow-Credentials option. I found that necessary with my need, which was to enable access to a SignalR hub on a remote Azure webserver/app instance.

Good luck!



来源:https://stackoverflow.com/questions/28663667/enable-cors-in-azure-web

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