Cross origin resource sharing Asp.net Web API


Introduction 

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

Cross Origin Resource Sharing (CORS) 

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than other techniques. 

Enable CORS 

  • Install-Package Microsoft.AspNet.WebApi.Cors 
  • Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method: 
     

 Scope Rules for [EnableCors] 

  • Per Action 
  • Per Controller 
  • Globally 
  

Per Action 

To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only. 

Per Controller 

If you set [EnableCors] on the controller class, it applies to all the actions on the controller. To disable CORS for an action, add the [DisableCors] attribute to the action. The following example enables CORS for every method except PutItem. 


Globally 

To enable CORS for all Web API controllers in your application, pass an EnableCorsAttribute instance to the EnableCors method: 


#Web #API #Restful #Service #RestAPI #core #API2

Post a Comment

Previous Post Next Post