enable cors in web api config

enable cors in web api config

in this article, i will show you how to enable cors in web api config

nowadays, asp.net web api is a trending technology. everyone is trying to access the service through ajax requests or server-side. problem is when a web api is hosted and the other application (different domain) tries to access the web api through an ajax request. security restrictions on your browser’s security policy prevent your web browser from making ajax requests to a server in another domain. here, enabling cors plays a vital role in web api.

what is cors?

cors (cross-origin resource sharing) comes to the rescue. cors is a w3c the standard that allows you to get away from the same-origin policy adopted by the browsers to restrict access from one domain to resources belonging to another domain. you can enable cors for your web api using the respective web api package (depending on the version of web api in use) or owin middleware.

note that the origin of a request is comprised of a scheme, a host, and a port number. so, two requests are considered to be from the same origin if they have the same scheme, host, and port number.

what is the same-origin policy?

 browsers allow a web page to make ajax requests only within the same domain. browser security prevents a web page from making ajax requests to another domain. this is called origin policy.

 we can enable cors in web api,

(i)using JSONP

to install this package, you can execute the following command from the NuGet package manager console.

--Install-Package WebApiContrib.Formatting.Jsonp

after adding jsonp package, we need to add the following code-snippet in the App_Start\WebApiConfig.cs file. it creates an instance of JsonpMediaTypeFormatter class and adds to the config formatters object.

var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);                          config.Formatters.Add(jsonpFormatter);

after adding configuration change ajax request datatype: jsonp

(ii)using CORS 

--Install-Package Microsoft.AspNet.WebApi.Cors

support for CORS can be enabled at three levels. these include the following: 

Global level: 

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");

config.EnableCors(cors);

Controller level:

[EnableCors(origins: "*", headers: "*", methods: "*")]

Action level:

you might need to disable CORS for a specific action or a group of actions

[DisableCors()]

or :

-add this code web.config in <system.webServer> tage

  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods"
           value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

Post a Comment

0 Comments