从JQuery调用WCF服务不起作用

时间:2014-01-27 13:50:50

标签: c# jquery wcf

问题是如何从JQuery访问非aspx服务。

我尝试了什么:

最简单的案例:

合同:

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

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

服务: 使用系统; 使用System.ServiceModel.Web;

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

托管服务:

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();
        }
    }

如果我尝试使用wcftestclient访问服务,我可以访问数据。

现在我尝试通过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>

我认为应该发生的是我得到了一个Hello世界。但事实并非如此。

我试过了:

$.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); }
    }
});

我得到的是两个警告“[Object] object”和“Error:Status:0”

所以在这种情况下,它似乎遇到了一些错误,但在哪?

之前我从未使用过jquery,那么有什么地方可以获得更多有用的错误消息吗?

我是否需要在wcf服务中定义其他内容?

最后,两个项目不应该在同一个应用程序中。 JQuery应该在客户端使用,而wcf服务在集中式服务器上运行。

如果我改变

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

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

我可以看到WCF服务器上的调试点已到达(文本返回) - 但仍显示两个错误对话框。

(补充:localhost:22334 / TheService / Get在浏览器中返回“Hello World” - 因此我认为这是JQuery / Ajax的问题​​,还是?)


更新

对应回复和http://pranayamr.blogspot.de/2011/06/calling-cross-domain-wcf-service-using.html我添加了以下内容:

将Debug设置为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;
    }
}

将行为改为asp兼容性

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 });

允许crossdomainscriptaccess

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

并尝试设置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); }
    }
});

现在它似乎以某种方式工作。 (如果出现问题,仍然没有真正的错误信息......)(而且似乎也不需要asp部分......)

1 个答案:

答案 0 :(得分:1)

相关问题