João Pinto
João Pinto

Reputation: 1998

CORS issue with Angular Client and ASP.NET Web API

I have a client side application built with AngularJS that is consuming services from a RESTful ASP.NET Web API. So far so good. I have created both of them under the same solution on Visual Studio, the API is an ASP.NET project and the AngularJS is a website. Both projects have to work using windows authorization so I created the API with windows authorization as the default AA mechanism in the project creator wizard, and for the AngularJS I have enable windows authentication on the properties tab of the project.

In order to test the communication between the two applications I decided to build a simple service. I created a Quotation model class, built the controller for it, and then added migrations and added some quotations in the database. I then tried to send a get request from the angular application only to receive this error:

enter image description here

After studying this issue I realized that I had to enable CORS on the web API. So I went to NuGet Package Manager and added the Microsoft.AspNet.Cors package to the project.

enter image description here

I then enabled CORS on the WebApiConfig.cs like this:

namespace Web_API
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.EnableCors();

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

And I added the header to my controller class and method (just in case on the class wasn't enough):

namespace Web_API.Controllers
{
    [EnableCors("*", "*","*")]
    public class QuotationsController : ApiController
    {
        private Web_APIContext db = new Web_APIContext();

        // GET: api/Quotations
        [EnableCors("*", "*", "*")]
        public IQueryable<Quotation> GetQuotations()
        {
            return db.Quotations;
        }

However, I still get the same error when I make a get request from the AngularJS application. Does anyone know how to fix this issue?

Upvotes: 0

Views: 470

Answers (1)

Sk. Tajbir
Sk. Tajbir

Reputation: 290

can you please try this:

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

Also don't use EnableCors in your method. As you've used this on your controller, by default all methods will fall under this rule.

I hope this will solve your problem. Thanks.

Upvotes: 1

Related Questions