Sunday, October 29, 2017

No 'Access-Control-Allow-Origin' header is present on the requested resource.

When we create a web API and it works fine in our local application or the same application but if we want that same API to use in the different application then we come across an error known as the 'Access-Control-Allow-Origin'

Please look at the below image


Failed to load http://localhost:4815/api/v1/user/hello: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

To solve that error we need to do the following thing.By setting the cors we are allowing the other users to access our web API we can set the restriction also on the controllers or on the methods of our web API so that users can only access the content which we want them to access. Please find the ways how to enable cors in your application.

First, install the library  Nuget Package Link


Then add the below namespace in your application

using System.Web.Http.Cors;

After adding the namespace you will able to access the EnableCors attribute

[RoutePrefix("API/v1/user")]
    [EnableCors("*", "*", "GET,POST")] //add this line
    public class UserController : ApiController
    {
        [HttpGet]
        [Route("Hello")]
        public HttpResponseMessage Hello()
        {

            return Request.CreateResponse(HttpStatusCode.OK,"I'm from WebAPI");
        }

    }


Also, go to the web API config and add this lines

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

            // Web API routes
            config.MapHttpAttributeRoutes();

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


            EnableCorsAttribute co = new EnableCorsAttribute("*", "*", "GET,POST"); //add this line
            config.EnableCors(co); //add this line

        }
    }

No comments:

Post a Comment

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...