Search code examples
jqueryjsoncross-domainwcf-rest

jQuery cross domain post to WCF 4.0 REST service


I'm trying to post JSON data from JQuery to a cross domain WCF 4.0 REST service and cannot get past the cross domain aspect. Here's my REST method:

    [OperationContract]
    [WebInvoke(Method = "*",
         BodyStyle = WebMessageBodyStyle.Bare,
         RequestFormat = WebMessageFormat.Json
         ResponseFormat = WebMessageFormat.Json,
         UriTemplate = "Save")]
    DataContract Save(DataContract dataContract);

Here's my jQuery code:

$.ajax(
{
type: 'POST',
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(data)
{
    alert('success');
},
error:function (xhr, ajaxOptions, thrownError)
{
    alert(xhr.status);  
    alert(thrownError);
} });   

I've stumbled across this post but could not get it to work. Please help.

Thanks

Tom


Solution

  • For what it's worth, in IIS 7, I created a "sub application" to my web site named "Rest" and pointed it to where my WCF Rest Service code lives (in my case C:\inetpub\wwwroot\RestServices). Then I changed all of my service calls in my website to use the same domain but appended "\Rest\" to the URL.

    URL to website: http://local.companyapp.com/

    URL to REST Services: http://local.companyapp.com/Rest/ServiceLibrary/Save

    Before, I was trying to access: http://local.RestServices.com/ServiceLibrary/Save

    It wasn't working because it was a different domain(local.RestServices.com) it was failing. Changing IIS to have a "sub application" named "Rest" that points to where my Rest Services resides fixes the problem.

    I'm not sure what issue I will run into once I'm ready to promote this to production. On the surface I like this approach because it doesn't force me to modify my code to handle the weirdness surrounding cross domain requests.

    Any comments on this is much appreciated. Thanks