Web applications are more vulnerable to security risks.Browsers impose some restrictions to make web applications secure.One such security measure is calledsame origin policy.Same origin policy prevents a web page to make AJAXrequests to different domain.
This means the web page in the following website
http://www.SampleSite1.com/
can not make ajax requests to
http://www.SampleSite2.com/
Same origin policy is useful as it helps prevents security vulnerabilities such as cross site scripting attack.But in some scenarios we may want to allow our serviceor method to be called by method or web page in a different domain.In such cases we can allow cross domain requests by using CORS or Cross Origin Resource Sharing.CORS can be usedin WebAPI 2.
Implementing CORS in WebAPITo enable CORS follow the below steps
1.Add the nuget package for CORS using the following command
Install-Package Microsoft.AspNet.WebApi.Cors2.Enable CORS by calling the EnableCors() method of HttpConfiguration class in the WebApiConfig.Register() method as:
config.EnableCors(); 3.Add the [EnableCors] attribute to the Controller class as: [EnableCors(origins: "http://www.SampleSite2.com", headers: "*", methods: "*")] public class SampleController : ApiController {}In the EnableCors attribute we specify the domain which we want to enable for CORS.In this example action methods in SampleController can be called throughAJAX inwww.SampleSite2.com.