CORS in WebAPI 2
Web applications are more vulnerable to security risks.Browsers impose some restrictions to make web applications secure.One such security measure is called same origin policy.Same origin policy prevents a web page to make AJAX requests to different domain.
This means the web page in the following website
can not make ajax requests to
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 service or 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 used in WebAPI 2.
Implementing CORS in WebAPI
To enable CORS follow the below steps
1.Add the nuget package for CORS using the following command
2.Enable CORS by calling the EnableCors() method of HttpConfiguration class in the WebApiConfig.Register() method as:
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 through AJAX in www.SampleSite2.com.