XMLHttpRequest cannot load http://*****/api/***.'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://*****therefore not allowed access.
Solution:
enable cors on you web api application .
Steps:
Goto top right corner of your visual studio and type package manager console.
select package manager console and it opens up console at the bottom of vs as error List/output show up generally
step 2: type the following command :
Install-Package Microsoft.AspNet.WebApi.Cors
it may ask for say yest to all as this package going to add some code and make some changes to application if you are using tfs if may request you to accept the changes and say yes to all .
once installation is done you will see warnings in you error list and just by double clicking these error it included the missing references and evrything should be good .
step 3:
build and see if everything works fine.
step 4:
now add this code in webconfig.cs files (location --> app_Start )
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
setp 5:
add following code to enable cors for that controller you can enable cors at controller level or method level .
Allow all client request :
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
}
Allow client request from http://abc domain:
[EnableCors(origins: "http://abc", headers: "*", methods: "*")]
public class TestController : ApiController
{
}
Allow client request from http://abc and http://fgh domain:
[EnableCors(origins: "http://abc, http://fgh", headers: "*", methods: "*")]
public class TestController : ApiController
{
}
we can disable this cors to specifi methods in controller for security resons by simply
[DisableCors]
public method ()
{
}
Even More options :
[EnableCors(origins: "http://mysite.mydomain.com, http://clientsite.clientdomain.com", "*","PUT,POST")]
Comments
Post a Comment