7

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>
1
  • I am having the same problem here, how did you solved your isssue? Thanks. Commented Mar 1, 2013 at 8:13

6 Answers 6

14

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Worked for my on both my WCF REST and SOAP web services :)
3

This link would help: http://enable-cors.org/

You need to add the following headers in your response that is sent back to the client:

//Allow all domains

Access-Control-Allow-Origin: *

OR

//Allow specific domains

Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com

3 Comments

Also it should be dataType not datatype. Also after the above try putting the response in script tag if it isn't wrapped on the server
ok so I Added the configuration to my project but still without send the header to the client i updated my question with my configuracion
same here, I added that same couple of custom classes and it does hit that logic but the response still does not have the headers.
2

the solution is to create a file Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE");

        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

Comments

1

I was getting the same problem when working with my WCF service directly in Visual Studio, in Chrome and Firefox. I fixed it with the following:

Edit the Global.asax file with below function:

            private void EnableCrossDomainAjaxCall()
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

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

Then call the function from

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
       EnableCrossDomainAjaxCall();
    }

You can get more information from the following url:

http://blog.blums.eu/2013/09/05/restfull-wcf-service-with-cors-and-jquery-and-basic-access-authentication.

Comments

0

Another way of handling this, which is better for self-hosted services, can be found here.

Comments

0

For WCF service you have to develop new behavior and include it in the endpoint configuration:

  1. Create Message Inspector

        public class CustomHeaderMessageInspector : IDispatchMessageInspector
        {
            Dictionary<string, string> requiredHeaders;
            public CustomHeaderMessageInspector (Dictionary<string, string> headers)
            {
                requiredHeaders = headers ?? new Dictionary<string, string>();
            }
    
            public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
            {
                return null;
            }
    
            public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
                foreach (var item in requiredHeaders)
                {
                    httpHeader.Headers.Add(item.Key, item.Value);
                }           
            }
        }
    
  2. Create Endpoint Behavior and use Message Inspector to add headers

        public class EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior
        {
            public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
            {
    
            }
    
            public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
            {
    
            }
    
            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
            {
                var requiredHeaders = new Dictionary<string, string>();
    
                requiredHeaders.Add("Access-Control-Allow-Origin", "*");
                requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
                requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
            }
    
            public void Validate(ServiceEndpoint endpoint)
            {
    
            }
    
            public override Type BehaviorType
            {
                get { return typeof(EnableCrossOriginResourceSharingBehavior); }
            }
    
            protected override object CreateBehavior()
            {
                return new EnableCrossOriginResourceSharingBehavior();
            }
        }
    
  3. Register new behavior in web.config

    <extensions>
     <behaviorExtensions>        
                <add name="crossOriginResourceSharingBehavior" type="Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral" />        
      </behaviorExtensions>      
    </extensions>
    
  4. Add new behavior to endpoint behavior configuration

    <endpointBehaviors>      
     <behavior name="jsonBehavior">
      <webHttp />
       <crossOriginResourceSharingBehavior />
     </behavior>
    </endpointBehaviors>
    
  5. Configure endpoint

    <endpoint address="api" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="Service.IServiceContract" />
    

1 Comment

I also facing the same issue and I used you code and now i m facing below error "The type 'Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral' registered for extension 'crossOriginResourceSharingBehavior' could not be loaded"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.