Quantcast
Channel: CodeSection,代码区,网络安全 - CodeSec
Viewing all articles
Browse latest Browse all 12749

CORS in WebAPI 2

$
0
0

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 WebAPI

To enable CORS follow the below steps

1.Add the nuget package for CORS using the following command

Install-Package Microsoft.AspNet.WebApi.Cors

2.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.


Viewing all articles
Browse latest Browse all 12749

Latest Images

Trending Articles



Latest Images