{"id":586,"date":"2015-08-31T12:20:00","date_gmt":"2015-08-31T12:20:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=586"},"modified":"2025-02-18T14:37:30","modified_gmt":"2025-02-18T14:37:30","slug":"enable-cors-in-asp-net-web-api","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/enable-cors-in-asp-net-web-api","title":{"rendered":"How To Enable Cors in the asp.net Web API?"},"content":{"rendered":"\n<p>Have you ever come across the following error:<\/p>\n\n\n\n<p><strong>Cross-Origin Request Blocked. The same origin policy disallows reading the resource<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Scheme (HTTP)<\/li>\n\n\n\n<li>Host (server)<\/li>\n\n\n\n<li>Port (8888)<\/li>\n<\/ol>\n\n\n\n<p>The Origin consists of the Scheme, Host, and the Port number.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/7217.picture_5F00_1_5F00_DJ.png\" alt=\" The Origin consists of the Scheme, Host, and the Port number.\" title=\"The Origin consists of the Scheme, Host, and the Port number.\"\/><\/figure>\n\n\n\n<p>If two resources have the same combination of scheme, host, and port then they are considered of the same origin, else of the cross-origin.\u00a0\u00a0Let us consider the following two URI<\/p>\n\n\n\n<p><a href=\"http:\/\/abc.go.com\/\" rel=\"noopener\">http:\/\/abc.com:80<\/a>\u00a0and\u00a0<a href=\"http:\/\/gen.xyz\/\" rel=\"noopener\">http:\/\/xyz.com:8080<\/a>\u00a0are not of the same origin since their host and port are not the same. For the security reason resource sharing between these two URL may be restricted. Let us try to understand CORS with the example of XMLHttpRequest. We use the XMLHttpRequest to perform the\u00a0\u00a0HTTP operation on the server from the HTML document. There are two URLs used in the XMLHttpRequest:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li> Requested URL or URL of the server<\/li>\n\n\n\n<li> URL of the document which initiated the request<\/li>\n<\/ol>\n\n\n\n<p>If both URLs have the same scheme, host, and port then XMLHttpRequest object will perform the operation else it will block the HTTP operation for security reasons.<\/p>\n\n\n\n<p>Both the server and the browser must have the support of the CORS. By default, all recent browsers have CORS support, but as an API developer, we need to enable support of CORS in the Web API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"cors-in-asp-net-web-api\">CORS in ASP.NET Web API<\/h2>\n\n\n\n<p class=\"CxSpFirst\">Here we have created a very simple ASP.NET Web API which returns an array of classes as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/2818.picture_5F00_2_5F00_DJ.png\" alt=\" created a very simple ASP.NET Web API which returns an array of classes\" title=\"created a very simple ASP.NET Web API which returns an array of classes\"\/><\/figure>\n\n\n\n<p>As you can see that Web API is running on port 8458.\u00a0\u00a0Next, we are trying to get the data in a JavaScript application which is running on the URI with the port 5901:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/4087.picture_5F00_3_5F00_DJ.png\" alt=\" we are trying to get the data in a JavaScript application which is running on the URI with the port 5901\" title=\"we are trying to get the data in a JavaScript application which is running on the URI with the port 5901\"\/><\/figure>\n\n\n\n<p>In the HTML document, we are using an XMLHttpRequest object to make the HTTP call. As it is evident that URI of Web API (URI of the resource requested) and the HTML document (URL from which the request originated) are not the same hence XMLHttpRequest object is blocking the resource sharing since they are not of the same origin. Very likely in the browser we will get the exception as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/1348.picture_5F00_4_5F00_DJ.png\" alt=\" \"\/><\/figure>\n\n\n\n<p>Let us dig further into the bug. In the browser, open the developer tool and the network tab. You will find Origin and Host in Request Header as shown in the image below. It is clear that both are not the same, and CORS is not allowed by the user agent XMLHttpRequest.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/5141.picture_5F00_5_5F00_DJ.png\" alt=\" CORS is not allowed by the user agent XMLHttpRequest\" title=\"CORS is not allowed by the user agent XMLHttpRequest\"\/><\/figure>\n\n\n\n<p>If you look at the Response Header there would be no information about Access-Control-Allow-Origin.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/0361.picture_5F00_6_5F00_DJ.png\" alt=\" look at the Response Header there would be no information about Access-Control-Allow-Origin\" title=\"look at the Response Header there would be no information about Access-Control-Allow-Origin\"\/><\/figure>\n\n\n\n<p>Since the server does not send a response about which origin can access the resource in the header, XMLHttpRequest object blocks the resource sharing in the browser.\u00a0\u00a0Let us go ahead and enable the CORS support for the Web API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"enabling-cors-in-asp-net-web-api\">Enabling CORS in ASP.NET Web API<\/h2>\n\n\n\n<p>To enable CORS in ASP.NET Web API 2.0, first, you need to add the Microsoft.AspNet.WebApi.Cors package to the project. Either you can choose the command prompt to install the package or NuGet manager to search and install as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/5148.picture_5F00_7_5F00_DJ.png\" alt=\" To enable CORS in ASP.NET Web API 2.0, first, you need to add the Microsoft.AspNet.WebApi.Cors package to the project\" title=\"To enable CORS in ASP.NET Web API 2.0, first, you need to add the Microsoft.AspNet.WebApi.Cors package to the project\"\/><\/figure>\n\n\n\n<p class=\"CxSpFirst\">You can configure CORS support for the Web API at three levels:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li> At the Global level<\/li>\n\n\n\n<li> At the Controller level<\/li>\n\n\n\n<li>At the Action level<\/li>\n<\/ol>\n\n\n\n<p class=\"CxSpMiddle\">To configure CORS support at the global level, first, install the CORS package and then open\u00a0<strong>WebApiConfig.cs<\/strong>\u00a0file from\u00a0<strong>App_Start<\/strong>\u00a0folder.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var cors = new EnableCorsAttribute(\"http:\/\/localhost:5901\", \"*\", \"*\");\nconfig.EnableCors(cors);<\/pre>\n\n\n\n<p class=\"CxSpLast\">After enabling CORS at the global level, again host the Web API and examine the request and response header. Also, notice that in the Enable CORS attribute we have set the Origin URL to the URL of the JavaScript App.<\/p>\n\n\n\n<p class=\"CxSpLast\">The Web API server is adding an extra header Access-Control-Allow-Origin in the response header as shown in the image below. The URL in the Access-Control-Allow-Origin header in the response header and the URL in the Origin header in the request header must be same then only XMLHttpRequest will allow the CORS operations. In some cases, the value of the&nbsp;&nbsp;Access-Control-Allow-Origin response header will be set to a wildcard character*. This means the server allows CORS support for all the origins instead of a particular origin.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/6644.picture_5F00_8_5F00_DJ.png\" alt=\" Web API server is adding an extra header Access-Control-Allow-Origin\" title=\"Web API server is adding an extra header Access-Control-Allow-Origin\"\/><\/figure>\n\n\n\n<p>We have enabled the CORS support on the server, so we should not get the exception and data should be fetched in the browser.<\/p>\n\n\n\n<p>As we discussed earlier, in the ASP.NET Web API, CORS support can be enabled at three different levels:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>At the Action level<\/li>\n\n\n\n<li><span style=\"line-height: normal;\"><span style=\"font-family: Times New Roman;\"><span style=\"font-size: 7pt;\"> <\/span><\/span><\/span>At the Controller level<\/li>\n\n\n\n<li>At the Global level<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"enable-cors-at-the-action-level\">Enable CORS at the Action level<\/h2>\n\n\n\n<p>CORS support can be enabled at the action level as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[EnableCors(origins: \"http:\/\/localhost:5901\", headers: \"*\", methods: \"*\")]\npublic HttpResponseMessage GetItem(int id)\n{\n   \/\/ Code here\n}<\/pre>\n\n\n\n<p>In the above code listing, we have enabled CORS for the GetItem action. Also, we are setting parameters to allow all the headers and support all the HTTP methods by setting the value to star.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"enable-cors-at-the-controller-level\">Enable CORS at the Controller level<\/h2>\n\n\n\n<p>CORS support can be enabled at the controller level as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[EnableCors(origins: \"http:\/\/localhost:5901\", headers: \"*\", methods: \"*\")]\npublic class ClassesController : ApiController {}<\/pre>\n\n\n\n<p>In the above code listing, we have enabled CORS for the Classes Controller. We are also setting parameters to allow all the headers and support all the HTTP methods by setting the value to star. We can exclude one of the actions from CORS support using the [DisableCors] attribute.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"enable-cors-at-the-global-level\">Enable CORS at the Global level<\/h2>\n\n\n\n<p>To configure CORS support at the global level, first install the CORS package and then open the\u00a0<strong>WebApiConfig.cs<\/strong>\u00a0file from\u00a0<strong>App_Start<\/strong>\u00a0folder.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var cors = new EnableCorsAttribute(\"http:\/\/localhost:5901\", \"*\", \"*\");\nconfig.EnableCors(cors);<\/pre>\n\n\n\n<p>If you set the attribute in more than one scope, the order of precedence is as follows:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.Maria_5F00_Blogs\/1030.picture_5F00_9_5F00_DJ.png\" alt=\" set the attribute in more than one scope, the order of precedence\" title=\"set the attribute in more than one scope, the order of precedence\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"attributes-of-enablecors\">Attributes of EnableCors<\/h2>\n\n\n\n<p class=\"CxSpFirst\">1.<span style=\"line-height: normal;\"><span style=\"font-family: Times New Roman;\"><span style=\"font-size: 7pt;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/span><\/span><\/span>Origins: You can set more than one origins value separated by commas.&nbsp; If you want any origin to make AJAX request to the API then set origin value to wildcard value star.<\/p>\n\n\n\n<p class=\"CxSpMiddle\">2.<span style=\"line-height: normal;\"><span style=\"font-family: Times New Roman;\"><span style=\"font-size: 7pt;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/span><\/span><\/span>Request Headers: The Request header parameter specifies which Request headers are allowed. To allow any header set value to *<\/p>\n\n\n\n<p class=\"CxSpLast\">3.<span style=\"line-height: normal;\"><span style=\"font-family: Times New Roman;\"><span style=\"font-size: 7pt;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/span><\/span><\/span>HTTP Methods: The methods parameter specifies which HTTP methods are allowed to access the resource. To allow all methods, use the wildcard value \u201c*\u201d. Otherwise set comma separated method name to allow set of methods to access the resources.<\/p>\n\n\n\n<p>Putting that all together, you can enable CORS for two origins, for all the headers, and then post and get operations as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[EnableCors(origins: \"http:\/\/localhost:5901,http:\/\/localhost:8768\", headers: \"*\", methods: \"post,get\")]\npublic class ClassesController : ApiController {}<\/pre>\n\n\n\n<p>Optionally you can also pass credentials to the Web API and create a custom policy, but I hope you found this post about the basics of CORS in the ASP.NET Web API. Have something to add? Share your comments below!<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"\/downloads\/request\/00000000-0000-0000-0000-000000005656?p=asp.net\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" src=\"https:\/\/download.infragistics.com\/marketing\/Blog-in-content-ads\/ASP.NET\/Blog-in-content-ASP-650x200.jpg\" alt=\" \"\/><\/a><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Consider this the simplest how-to guide to enabling CORS in your APS.NET Web API. Check out all the steps in this article and learn more today.<\/p>\n","protected":false},"author":65,"featured_media":1219,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-586","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-how-to"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/586","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=586"}],"version-history":[{"count":2,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/586\/revisions"}],"predecessor-version":[{"id":1903,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/586\/revisions\/1903"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/1219"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=586"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=586"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=586"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}