Issue in Enabling CORS for Web API 1, .net 4.0

I need to enable CORS for my Web API and I can’t upgrade to Framework 4.5.
I’ve tried to add the following to my Web.config to see if it worked, but it didn’t:

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept,Content-Type,X-Requested-With"/>

I am accessing the URL http://localhost:8484/api/values/ from ajax call

and getting bellow error

XMLHttpRequest cannot load http://localhost:8484/api/values. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. The response had HTTP status code 405.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I found this simple solution by charanjit singh.
It worked nicely especially if you are stuck with older visual studio 2010 , on .Net 4.0 and of course web api 1.
Basically add this function to your Global.asax.cs

protected void Application_BeginRequest(object sender, EventArgs e)

{

    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                     "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                     "Content-Type, Accept");
        HttpContext.Current.Response.End();
     }
}

ref. links: note you must scroll to the bottom comments for the answer.
http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html

Method 2

Web API 1.0, you need to enable CORS support using the following statements in the Application_BeginRequest event handler of the Global.asax.cs file.

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin);

Support for CORS can be enabled at three levels. These include the following:

Action level
Controller level
Global level

refer link


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x