简体   繁体   中英

Calling WCF Service from JQuery does not work

Problem is how to access a non aspx service from JQuery.

What i have tried:

Easiest case:

Contract:

using System.ServiceModel;
using System.ServiceModel.Web;

namespace TheService
{
    [ServiceContract]
    public interface ITheService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        string Get();
    }
}

The Service: using System; using System.ServiceModel.Web;

namespace TheService
{
    public class TheService : ITheService
    {
        public string Get()
        {
            return "Hello, world!";
        }
    }
}

Hosting the service:

class Program
    {
        static void Main(string[] args)
        {
            Uri httpUrl = new Uri("http://localhost:22334/TheService");

            ServiceHost host = new ServiceHost(typeof(TheService), httpUrl);

            ServiceMetadataBehavior serviceMetaDataBehaviour = new ServiceMetadataBehavior
            {
                HttpGetEnabled = true,
                MetadataExporter = {PolicyVersion = PolicyVersion.Policy15}
            };
            host.Description.Behaviors.Add(serviceMetaDataBehaviour);

            host.AddServiceEndpoint(typeof(ITheService), new WebHttpBinding(), "");

            host.Open();

            Console.ReadLine();
        }
    }

If i try to access the service with the wcftestclient, i can access the data.

Now i tried to access it via jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
      $(document).ready(function() {

  $.getJSON("http://localhost:22334/TheService/Get",
  function(data){
    alert("Data Loaded: " + data);
  });
});

  </script>
</head>
<body>

</body>
</html>

What I assumed that should happen is that I get a Hello world back. but it doesn't.

I tried:

$.ajax({
    type: "GET",
    url: "http://localhost:22334/TheService/Get", 
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert(msg);
    },
    error: function(err) {
        alert(err.toString());
        if (err.status == 200) {
            ParseResult(err);
        }
        else { alert('Error:' + err.responseText + '  Status: ' + err.status); }
    }
});

and all i got was two alerts "[Object] object" and "Error: Status: 0"

So in this case it seems that it runs into some error, but in which?

I have never used jquery before, so is there any where to get a little bit more helpful error message?

Do I need to define anything else in the wcf service?

At the end both projects should not be in the same aplication. the JQuery should be used at a client side and the wcf service run at a centralized server.

If i change

ServiceHost host = new ServiceHost(typeof(TheService), httpUrl);

to

WebServiceHost host = new WebServiceHost(typeof(ServiceCalculator), httpUrl);

i can see that a debug point at the WCF server is reached (return of the text) - but still both error dialogs are show.

(Added: localhost:22334/TheService/Get returns "Hello World" in browser - therefore i think it is either a problem with JQuery/Ajax, or ? )


Update:

Corresponding to the reply and http://pranayamr.blogspot.de/2011/06/calling-cross-domain-wcf-service-using.html i added the following:

Set Debug to true:

ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();

if (debug == null)
{
    host.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
}
else
{
    if (!debug.IncludeExceptionDetailInFaults)
    {
        debug.IncludeExceptionDetailInFaults = true;
    }
}

change behaviour to asp compatibility

for (int i = 0; i < host.Description.Behaviors.Count; i++)
{
    if (host.Description.Behaviors[i] is AspNetCompatibilityRequirementsAttribute)
    {
        host.Description.Behaviors.RemoveAt(i);
        break;
    }
}
host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute { RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed });

allow crossdomainscriptaccess

host.Description.Behaviors.Add(serviceMetaDataBehaviour);
WebHttpBinding binding = new WebHttpBinding {CrossDomainScriptAccessEnabled = true};
host.AddServiceEndpoint(typeof(IServiceCalculator), binding, "");

and tried to set jsonp

$.ajax({
    type: "GET",
    url: "http://localhost:22334/TheService", 
    method: "Get",
    contentType: "application/json; charset=utf-8",
    dataType: 'jsonp',
    success: function(msg) {
        alert(msg);
    },
    error: function(err) {
        alert(err.toString());
        if (err.status == 200) {
            ParseResult(err);
        }
        else { alert('Error:' + err.responseText + '  Status: ' + err.status); }
    }
});

Now it seems to work somehow. (Still getting no real error information if something goes wrong...) (and the asp part does not seem to be needed also..)

You might have run into a cross-domain request ( http://www.d-mueller.de/blog/cross-domain-ajax-guide/ ).

Try CORS ( http://en.wikipedia.org/wiki/Cross-origin_resource_sharing ) or JSONP ( http://en.wikipedia.org/wiki/JSONP ) or something of the like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM