logeyg
logeyg

Reputation: 559

Angular, WebAPI, and CORS

I am running a web application with angular that needs to call a separate ASP.NET Web API application to retrieve data. They are both running on different ports: (web server) 44302, and (web api server) 44307. I understand that to do this, CORS needs to be enabled on the web API server, which I have done my best to set up correctly:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

and on the ApiController:

[EnableCors(origins: "http://localhost:44302", headers: "*", methods: "*")]
    public class ClientController : ApiController
    {

    // GET: Client
    public IEnumerable<Client> Get()
    {
        ...
    }
    ...

Additionally, I have added this to angular:

$httpProvider.defaults.useXDomain = true;

Unfortunately, a simple API call from angular still returns a 404 error..

this.getClients = function() {
        return $http.get('/api/client');
    }

When entering localhost:44307/api/client into the browser, everything works as expected. What am I missing? I've searched tutorial upon tutorial to find something I'm not doing correctly, but it seems like I've included everything.

Upvotes: 1

Views: 303

Answers (1)

Morteza Zabihi
Morteza Zabihi

Reputation: 3054

Don't Enable CORS as you mentioned.

Do it as follows:

At the Global.asax, add the following method to configure CORS:

        protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Accept");
            HttpContext.Current.Response.End();
        }
    }

and it's done!

Upvotes: 2

Related Questions