【问题标题】:calling a simple WCF Service from jQuery从 jQuery 调用一个简单的 WCF 服务
【发布时间】:2011-10-01 16:32:49
【问题描述】:

我有一个名为pilltrkr.svc 的非常简单的WCF 服务。我正在尝试通过以下代码从 jQuery 调用此服务:

    var jsondata = JSON.stringify();
    $.ajax({
        type: "POST",
        async: false,
        url: './pilltrakr.svc/DoWork/',
        contentType: "application/json; charset=utf-8",
        data: jsondata,
        dataType: "json",
        success: function (msg) {
            alert(msg);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //                        alert(XMLHttpRequest.status);
            //                        alert(XMLHttpRequest.responseText);
        }
    });

我在本地执行此操作(因此使用本地主机)。 DoWork 只返回一个字符串。当我调用这个函数时,我得到一个 http://localhost:57400/pilltrakr/pilltrakr.svc/DoWork/ 404 Not Found

如何调用我的 WCF 服务?我尝试了几种不同的变体(经过研究)。我能够使用方法(客户端)背后的代码调用此服务。我确信这是一件非常容易的事情。请指教。

更多代码 -

似乎 Stack 上的每个帖子都包含服务的接口和实际类,所以我也将它们放在这里,以防万一我遗漏了什么:

界面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;

namespace serviceContract
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "Ipilltrakr" in both code and config file together.
    [ServiceContract]
    public interface Ipilltrakr
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        string DoWork();

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        int addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType);
    }
}

类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using pillboxObjects;

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

namespace serviceContract
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "pilltrakr" in code, svc and config file together.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class pilltrakr : Ipilltrakr
    {


        string Ipilltrakr.DoWork()
        {
            return "got here";
        }


        int Ipilltrakr.addUser(string userName, string userPhone, string userEmail, string userPwd, string acctType)
        {
            userAccount ua = new userAccount();
            int uId;

            ua.userName = userName;
            ua.userPhone = userPhone;
            ua.userEmail = userEmail;
            ua.userPwd = userPwd;
            ua.userCreateDate = DateTime.Now;
            ua.userAccountType = acctType;

            uId = ua.add();

            return uId;
        }
    }
}

网络配置:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="xxxConnectionString" connectionString="Data Source=xxx;Initial Catalog=xxx;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_Ipilltrakr" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:57400/pilltrakr/pilltrakr.svc/pilltrakr"
        binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Ipilltrakr"
        contract="svcPilltrakr.Ipilltrakr" name="BasicHttpBinding_Ipilltrakr" />
    </client>
    <services>
      <service name="serviceContract.pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint contract="serviceContract.Ipilltrakr" binding="basicHttpBinding" address="pilltrakr" bindingNamespace="serviceContract"/>
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />

  </system.serviceModel>
</configuration>

【问题讨论】:

  • 我认为 WCF 服务默认是 SOAP 服务,直接从 Javascript 调用它们会很棘手。您可以考虑使用 webHttpBinding 或 WCF Web API 之类的东西,或通过 .asmx 代理 WCF 调用。
  • @Sii - 有大量通过 jQuery 调用 WCF 服务的示例。我想我只是错过了一些简单的东西,可以帮助我克服障碍。
  • west-wind.com/weblog/posts/2008/Apr/21/… 这个帖子可能对你有帮助...
  • @patel.milanb - 我尝试按照他的方式实现它,但我什么也没得到......而且现在我原来的 asp.net 调用不起作用......似乎他的示例是基于未显示的内容(端点)

标签: jquery wcf


【解决方案1】:

可能有点晚了,但几年前我写了几篇关于从 jQuery 调用 WCF 的博客文章。这也包括故障处理——许多文章都忽略了这一点。

Part onePart two

HTH

伊恩

【讨论】:

  • 我阅读了第 1 部分,这是一篇很棒的文章。我现在正在看第 2 部分。
【解决方案2】:

我想出了如何最终从 jQuery 调用我的简单 WCF 服务。看了这个链接,我找到了一些源代码:

http://www.west-wind.com/weblog/posts/2009/Sep/15/Making-jQuery-calls-to-WCFASMX-with-a-ServiceProxy-Client。此链接未提供来源,但它是引用此链接的另一个页面。

无论如何,我下载了代码并开始将我的代码与这个通过 jQuery 调用 WCF 服务的工作项目进行比较。我发现我的 web.config 文件太复杂了,所以我大大缩短了它。然后我也意识到我的方法不是公开的。所以我将它们公开,然后经过一些调整(即取出命名空间),页面开始返回我试图返回的简单字符串。

  <system.serviceModel>
    <services>
      <service name="pilltrakr" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint address="" behaviorConfiguration="pilltrakrAspNetAjaxBehavior" binding="webHttpBinding" contract="Ipilltrakr"/>        
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="pilltrakrAspNetAjaxBehavior">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>

【讨论】:

    【解决方案3】:

    我在谷歌上找到的,可能对你有帮助。

    $(document).ready(function() {
             $("#sayHelloButton").click(function(event){
                 $.ajax({
                     type: "POST",
                     url: "dummyWebsevice.svc/HelloToYou",
                     data: "{'name': '" + $('#name').val() + "'}",
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function(msg) {
                         AjaxSucceeded(msg);
                     },
                     error: AjaxFailed
                 });
             });
         });
              function AjaxSucceeded(result) {
                  alert(result.d);
              }
              function AjaxFailed(result) {
                  alert(result.status + ' ' + result.statusText);
              }  
    
    [WebMethod()]
    public static string sayHello()
    {
        return "hello ";
    } 
    

    【讨论】:

    • 这是 WCF 服务吗?还是经典的网络服务?
    • -1 未解决问题的性质并提供不相关的答案(即与 WCF Web 服务相关的问题,而不是经典的 ASP.NET Web 方法)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多