使用jQuery使用WCF服务

时间:2011-12-21 15:30:19

标签: jquery wcf

过去几天我一直在关注这个问题而无处可去。我已经尝试了各种各样的教程,由于各种原因,我无法得到任何工作。我想要做的就是使用jQuery从简单的HTML页面调用WCF服务。我现在得到的只是“糟糕的要求”。

我将所有内容托管在IIS中的同一个虚拟目录中,因此它绝对不是跨域问题。

这是我的web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
    <behavior name="ServiceBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="ServiceBehavior" name="WcfJqueryTest">
    <endpoint address="" binding="webHttpBinding" contract="WcfJqueryTest.IService" behaviorConfiguration="ServiceBehavior"/>
  </service>
</services>
 </system.serviceModel>
  <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

这是我的服务代码和界面

namespace WcfJqueryTest
{
[ServiceContract]
public interface IService
{

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

namespace WcfJqueryTest
{
public class Service : IService
{
    public string GetData()
    {
        return "Hello world";
    }
}
}

最后我的jQuery

function myFunction () {
$.ajax({
    type: "POST",
    url: "http://localhost/wcfjquerytest/service.svc/getdata",
    contentType: "application/json; charset=utf-8",
    processData: true,
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (xhr, status, error) {
        alert(status);
        alert(error);
    }
})
};

我尝试过很多教程并在各处搜索,但我仍然没有更聪明。任何指针都非常感激。

干杯,

尼尔。

1 个答案:

答案 0 :(得分:0)

您可以尝试此操作,右键单击您的svc文件,然后单击“查看标记”

<%@ ServiceHost 
    Language="C#" 
    Debug="true" 
    Service="MyService.Service" 
    CodeBehind="Service.svc.cs" 
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" //Add this line
%>

这将自动配置您的服务(它覆盖您在web.config中所做的设置)。

相关问题