We get this error when we are trying to get some data from another origin maybe via an AJAX call. In this post we will discuss the solutions for this error in detail and we will also discuss about Cross Origin Requests. Here I am going to use Visual Studio 2015, Web API 2. I hope you will like this.
Background
I hosted my Web API in a server, and what that API does is, it will just return the data in JSON format. But when I tried to consume this Web API via an Ajax call, I was getting the error “No ‘Access-Control-Allow-Origin’ header is present on the requested resource." I solved the same issues in different ways. Here I am going to share those.
Using the code
I assume that you have created a Web API and hosted it in your server. If you are new to Web API, you can always get some information from here Articles Related To Web API.
We all will have some situations where we need to fetch some data from another domain or another site, right? If it is from the same site, you won’t be facing any issues at all. Like you are calling an Ajax call from the page www.SibeeshPassion.com/Receiver.html to www.SibeeshPassion.com/Sender.html to get the data, here the origin is same. and therefore you will get the data. What happens is when the sender and receiver is not in the same origin, like you need to get the data from www.Microsoft.com by an Ajax call in www.SibeeshPassion.com/Receiver.html. The browser will not allow you to get the sensitive data from other domain, for security purposes your browser will return to you “No ‘Access-Control-Allow-Origin'”. To overcome this, we have something called Cross Origin Resource Sharing (CORS). Basically process of allowing other sites to call your Web API is called CORS. According to W3 Org CORS is a standard which tell server to allow the calls from other origins given. It is much more secure than using JSONP(Previously we had been using JSON for getting the data from other domains.).
Fix To No Access-Control-Allow-Origin header is present.
We can fix this issue in two ways,
- By using Microsoft.AspNet.WebApi.Cors
- By adding header informations in Web.config
We will explain both now.
By using Microsoft.AspNet.WebApi.Cors,
To work with this fix, you must include the package By using Microsoft.AspNet.WebApi.Cors from Manage Nuget window.
Now got to App_Start folder from your solution. Then click on the file WebApiConfig.cs, this is the file where we set the configuration for our Web API.
Then you can add the preceding codes in the static function Register.
- var cors = new EnableCorsAttribute("*", "*", "*");
- config.EnableCors(cors);
If you do this, the CORS will be applied globally for all the Web API controller you have. This is the easiest way of doing it. Now if you want to see the metadata of EnableCorsAttribute, you can see find it below.
- // Summary:
- // Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.
- //
- // Parameters:
- // origins:
- // Comma-separated list of origins that are allowed to access the resource. Use
- // "*" to allow all.
- //
- // headers:
- // Comma-separated list of headers that are supported by the resource. Use "*" to
- // allow all. Use null or empty string to allow none.
- //
- // methods:
- // Comma-separated list of methods that are supported by the resource. Use "*" to
- // allow all. Use null or empty string to allow none.
- public EnableCorsAttribute(string origins, string headers, string methods);
You can also try the same as below in the Register function. Here we are going to apply CORS for particular controller, which means it will be applied for all the actions in the controller. Before that make sure you have added the preceding code in your WebApiConfig.cs file.
- config.EnableCors();
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Converters;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Runtime.Serialization;
- using System.Text;
- using System.Web;
- using System.Web.Http.Cors;
- namespace APIServiceApplication.Controllers
- {
- [EnableCors(origins: "*", headers: "*", methods: "*")]
- public class DefaultController: ApiController {}
- }
- namespace APIServiceApplication.Controllers
- {
- [EnableCors(origins: "*", headers: "*", methods: "*")]
- public class DefaultController: ApiController
- {
- [DisableCors]
- public string XMLData(string id)
- {
- return "Your requested product" + id;
- }
- }
- }
- namespace APIServiceApplication.Controllers
- {
- public class DefaultController: ApiController
- {
- [EnableCors(origins: "*", headers: "*", methods: "*")]
- public string XMLData(string id)
- {
- return "Your requested product" + id;
- }
- }
- }
- <system.webServer>
- <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" />
- <add name="Access-Control-Allow-Credentials" value="true" />
- </customHeaders>
- </httpProtocol>
- </system.webServer>
- Access-Control-Allow-Origin (For Origin)
- Access-Control-Allow-Headers (For Headers)
- Access-Control-Allow-Methods (For Methods)
Now if you go to your server and check, you can see that all the things are configured perfectly. I have configured my API in my server IIS, so I am going to see my Response Header settings in IIS.
Go to command window and type inetmgr and click OK, your IIS will opened shortly, now find your Web API which you have already configured under Default Web Site. Before doing this, please make sure that you have configured IIS in your windows. If you don’t know how to configure, I strongly recommend you to read Configure IIS in Windows .
Go to Features View and double click on HTTP Response Headers under IIS category.
You can see all the settings has been configured there.
That’s all, now if you run your application, you will be able to fetch the data from your Web API.
Conclusion
Did I miss anything that you may think is needed? Have you ever faced this issue? Did you try Web API yet? I hope you liked this article. Please share with me your valuable suggestions and feedback.
Your turn. What do you think?
A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.






OvaisPosted Jan 23, 2020, 12:02 PM
I have tried web.config solution, but it didn't work for me. Do I need to work on other solution?
Tokhin TokhinPosted Aug 23, 2019, 1:25 AM
Thanks a lot, u saved my life. [DisableCors] worked for me after long try
kalu singh raoPosted Mar 15, 2016, 7:42 AM
Nice...
Sibeesh VenuPosted Mar 14, 2016, 12:14 PM
Mohammed Ibrahim Thanks much
Mohammed IbrahimPosted Mar 14, 2016, 4:02 AM
nice
Sibeesh VenuPosted Mar 14, 2016, 1:20 AM
Debendra Dash Thanks, Yes for the php, you need to set the headers in your .httaccess file.
Sibeesh VenuPosted Mar 14, 2016, 1:19 AM
Debasis Saha Thanks much
Sibeesh VenuPosted Mar 14, 2016, 1:19 AM
Sanjay Gupta Thanks a lot
Sibeesh VenuPosted Mar 14, 2016, 1:19 AM
Vignesh Mani Thanks a lot
Sibeesh VenuPosted Mar 14, 2016, 1:19 AM
Kashif Sohail Thanks much
Sibeesh VenuPosted Mar 14, 2016, 1:18 AM
Saillesh Pawar Thanks a lot. Yes we can set that in server side only. You can always use crossDomain: true, and beforeSend function to set header in jQuery Ajax if you want.
Debasis SahaPosted Mar 14, 2016, 12:47 AM
Nice share
Debendra DashPosted Mar 12, 2016, 1:51 AM
Thanks sibeesh my php clients are facing some problem in posting any file to the server they are getting error for enabling Cors..i dont know it would required the setting in their client code or server.I would try this in my server code....
Debasis SahaPosted Mar 12, 2016, 12:56 AM
Nice share
Debasis SahaPosted Mar 12, 2016, 12:56 AM
Nice sharr
Sanjay GuptaPosted Mar 12, 2016, 12:40 AM
Clear and concise. Thanks for posting!
Vignesh ManiPosted Mar 11, 2016, 5:40 PM
good
Kashif SohailPosted Mar 11, 2016, 2:37 PM
great, i was looking for it since last weekend
Saillesh PawarPosted Mar 11, 2016, 1:49 PM
Thanks for sharing the solution Sibeesh sir. I want to ask you if we try to use accessControl allow:true in ajax request does it make any sense? accessControlallow:true is needed to be done in server side only?