2

my project is : ASP.NET Web Api C# With Angular

i am trying to make simple http get with allow cross domains from angular client

the request :

$http.defaults.headers.common['X-Auth-Key'] = 'somekey';
$http.defaults.headers.common['X-Auth-Email'] = 'someuser';
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$http.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
return {
    GetDomains: function () {
      return  $http({
          method: "get",
          url: "https://api.cloudflare.com/client/v4/zones/cd7d068de3012345da9420df9514dad0/dns_records?page=3&per_page=20&order=type&direction=asc",
          responseType: 'json'
        }).then(function mySucces(response) {
            return response.data;
        })
    }
}
});

in the response i can see :

access-control-request-headers:access-control-allow-methods, access-control- allow-origin, x-auth-email, x-auth-key

and the error :

XMLHttpRequest cannot load https://api.cloudflare.com/client/v4/zones/cd7d068de3012345da9420df9514dad0/dns_records?page=3&per_page=20&order=type&direction=asc. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 400.

i am trying to do it with iis express with visual studio 2015

IIS Express applicationhost.config and Web.Config files have :

    <httpProtocol>
        <customHeaders>
            <clear />
            <add name="X-Powered-By" value="ASP.NET" />
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time"/>
                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
                <add name="Access-Control-Allow-Credentials" value="true"/>
        </customHeaders>
        <redirectHeaders>
            <clear />
        </redirectHeaders>
    </httpProtocol>

App_Start / WebApiConfig.cs file :

         var corsAttr = new EnableCorsAttribute("https://api.cloudflare.com", "*", "*");
        config.EnableCors(corsAttr);

and still the same error

i tried everything may be you can help me

thank you !

1 Answer 1

3

You need to enable CORS in your WebApi Backend as described in this article:

Enabling Cors

The necessary parts are to install the package for cors with this commamd:

Install-Package Microsoft.AspNet.WebApi.Cors

Then adding the needed methods to your Startup/WebConfig

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

And after that you need to enable Cors either application wide or specific for your controllers:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

To enable CORS globally you need to create a Cors Config as shown in this example:

public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("www.example.com", "*", "*");
    config.EnableCors(cors);
    // ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

sorry forgot to add it but i already configured EnableCors globaly see my update
Have you added this attribute exactly that way you wrote or is this a Typo? Because if the domain that needs to be enabled is api.cloudflare.com and you want to enable it on all requests from this site you need to write config.EnableCors(new EnableCorsAttribute("api.cloudflare.com", "*", "*"); . If you forgot the wildcards you won´t be able to connect. Also, from the question you wrote I think, that your origin is localhost so you at least have to enable this as allowed CORS Origin too, because the Origin is the address from the calling client.
Wow dude, this totally fixed my CORS issue. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.