Tuesday, November 28, 2017

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

Google chorme does not allow to call local Web api if they are running on different port.
If you need to enable it tou need to install Microsoft.AspNet.Cors from nuget.

And need to write two lines in WebApiConfig file.


var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);

Sample code

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

            // Web API routes
            config.MapHttpAttributeRoutes();

            var cors = new EnableCorsAttribute("*","*","*");
            config.EnableCors(cors);

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

            config.Formatters.JsonFormatter.SupportedMediaTypes
                .Add(new MediaTypeHeaderValue("text/html"));
        }

No comments:

Followers

Link