Getting blocked by CORS Policy Error even after adding it at Web API Controller

Updated on: October 03, 2019

If you have already added "[EnableCors(origins: "*", headers: "*", methods: "*")]" in your web API, but still you are getting following blocked by CORS error:

Error:

Access to XMLHttpRequest at 'http://yourAPIdomain dot com' from origin 'http://yourwebsite dot com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution:

Please make sure that you have added following code in your Web.API project:

In the Register() method of WebApiConfig.cs class, verify that following line is added as first line of this Register() method

config.EnableCors();

Above your Web API Controller class, verify EnableCors is added above the class declaration:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AccountController : ApiController

If you have already added above code, but still you are getting above error, then check for following:

1. Make sure you have added proper routing at controller and at action method level

2. You have added proper http request type attribute above the action method (e.g. HttpGet, HttpPost, HttpPut, HttpDelete)

3. Make sure that you have added "EnableCors" attribute at controller level or at action method level

Above fixes are shown in following two approaches, you can follow one of the approach as shown below:

Approach 1:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AccountController : ApiController
{
        [HttpPost]
        [EnableCors(origins: "*", headers: "*", methods: "*")]
        [Route("ValidateUser")]
        public bool ValidateUser(LoginModel loginModel)
       {
             return true;
       }
}

OR

Approach 2:

[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
        [HttpPost]
        [Route("ValidateUser")]
        public bool ValidateUser(LoginModel loginModel)
        {
               return true;
        }

}

After adding above line of code at controller and at action method level, then your blocked by CORS Policy issue will get solved.

Related Articles