使用jQuery消费WCF服务

时间:2015-05-16 22:18:34

标签: c# jquery wcf

我一直在努力尝试从WCF服务中获取数据而没有运气,我很感激你的帮助,这是我的代码,我总是得到" 0未定义"在ajax调用的错误函数中:

Service1.svc.cs

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    public string GetData()
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string output = "It worked";

        return serializer.Serialize(output); 
    }
}

IService1.cs

    [OperationContract]
    [System.ServiceModel.Web.WebInvoke(Method = "POST",
        ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    string GetData();

的Web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
          </behavior>
        </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="MyService.Service1">
        <endpoint address="" binding="webHttpBinding" contract="MyService.IService1" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
          </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
        </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

jQuery调用

<script type="text/javascript">

    $(document).ready(function () {
        CallMyService();
    });

    function CallMyService() {
        $.ajax({
            type: "POST",
            url: "http://localhost:54368/Service1.svc/GetData",
            data: '',
            dataType: "json",
            contentType: "application/json",
            success: ServiceSucceeded,
            error: ServiceFailed
        });
    }

    function ServiceFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }

    function ServiceSucceeded(result) {
        var resultObject = result.GetDataResult;
        alert(resultObject);
    }

</script>

如果我尝试通过添加服务引用来从C#项目中使用WCF服务,我就是这样:

无法找到引用合同的默认端点元素&#39; myReference.IService1&#39;在ServiceModel客户端配置部分中。这可能是因为没有为您的应用程序找到配置文件,或者因为在客户端元素中找不到与此合同匹配的端点元素。

它可能与错误有关吗? WCF服务在本地IIS中托管。

我只是不知道还有什么要检查。

更新

我刚刚找到解决方案,事实证明我需要使用以下代码在WCF服务解决方案中使用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();
        }
    }

如果localhost是您的WCF服务所在的位置,那么它就可以了!非常感谢那些告诉我Javascript调试器的人,这给了我线索!!!

1 个答案:

答案 0 :(得分:0)

<强>更新

我刚刚找到解决方案,事实证明我需要使用以下代码在WCF服务解决方案中使用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();
    }
}

如果localhost是您的WCF服务所在的位置,那么它就可以了!非常感谢那些告诉我Javascript调试器的人,这给了我线索!!!