从jQuery调用一个简单的WCF服务

前端之家收集整理的这篇文章主要介绍了从jQuery调用一个简单的WCF服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个非常简单的WCF服务叫做pilltrkr.svc.我试图通过以下代码从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);
        }
    });

我在本地做这个(所以使用localhost). 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 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>

解决方法

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

Part onePart two.

HTH

伊恩

猜你在找的jQuery相关文章