Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not add Access-Control-Allow-Origin to my WCF library Project

Tags:

jquery

c#

ajax

wcf

I'm trying to understand why this ajax called doesn't work

 $.ajax({
        type: 'GET',
        url: "http://localhost:8732/Design_Time_Addresses/InMotionGIT_NT.Address.Service/AddressService/json/capitalize",
        data: { streetAddress : JSON.stringify(streetAddress) , consumer :  JSON.stringify(consumer)} ,
        datatype: "jsonp",
        success: function (data) {
            $('body').append('<div>'+data.IDblah+' '+ data.prueba+'</div>');
            alert(data.IDblah);
        }

The service receive the data is correctly received and the response it's correct. Why am I doing wrong?

I tried adding this property to the ajax called but without success crossDomain : true

[OperationContract()]
[WebInvoke(Method="GET", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public string Capitalize(StreetAddress streetAddress,ConsumerInformation consumer)

The error that i'm getting it's the common

 XMLHttpRequest cannot load Origin http://localhost:50816 is not allowed by Access-Control-Allow-Origin.

UPDATE

I tried to add the header to the response by adding the configuracion in my App.config file but without success

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</system.webServer>
like image 333
Jorge Avatar asked May 25 '12 20:05

Jorge


People also ask

How do you add Access-Control allow Origin header in WCF?

How to do that? - Add global. asax file and add following code to Application_BeginRequest. Following is the code snippet. As you can see from above, i am allowing origin to "http://localhost", so that if javascript is placed in this domain and that is making call to WCF, then it will be allowed.

How do I fix not allowed by Access-Control allow origin?

In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple: Create a Chrome browser shortcut. Right click short cut icon -> Properties -> Shortcut -> Target.

How do I enable CORS in WCF REST service?

You can enable CORS on service hosted on IIS or IIS Express by adding following configuration in config file. After adding above configuration you should able to access service in client side codes like JavaScript.


Video Answer


1 Answers

Put this in the service side of your configuration file

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>
</system.webServer>

It works for me! Thanks!

like image 67
mashet Avatar answered Dec 04 '22 20:12

mashet