65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 jQuery 调用 WCF 服务

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (80投票s)

2010 年 12 月 2 日

CPOL

3分钟阅读

viewsIcon

533928

downloadIcon

17153

关于如何使用 jQuery 调用 Windows Communication Foundation 服务的指南

引言

本文演示了如何从 jQuery 客户端代码调用 Windows Communication Foundation (WCF) 服务,并指出了需要特别注意的地方。在开始阅读和遵循本文之前,请先阅读这篇博客文章,其中描述了如何创建 WCF 服务:创建、托管和使用 WCF 服务

步骤 1

创建 WCF 服务后,您需要在服务器类型类上指定 ASP.NET 兼容模式的属性,以便 WCF 服务像普通的 ASMX 服务一样工作并支持所有现有的 ASP.NET 功能。通过设置兼容模式,WCF 服务将必须托管在 IIS 上,并使用 HTTP 与其客户端应用程序通信。

在此处阅读更多详细信息:WCF Web HTTP 编程对象模型

以下代码行设置 ASP.NET 兼容模式

[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    // Your code comes here
}

Service.cs

[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


    public string[] GetUser(string Id)
    { 
        return new User().GetUser(Convert.ToInt32(Id));
    }
}

public class User
{

    Dictionary<int, string> users = null;
    public User()
    {
        users = new Dictionary<int, string>();
        users.Add(1, "pranay");
        users.Add(2, "Krunal");
        users.Add(3, "Aditya");
        users.Add(4, "Samir");
    }

    public string[] GetUser(int Id)
    {
        var user = from u in users
                   where u.Key == Id
                   select u.Value;

        return user.ToArray<string>();
    }

}

第二步

接下来,您需要在服务合约文件中为每个方法或操作指定操作级别的属性。为此,使用 WebInvoke 修饰方法,该属性将服务操作标记为响应除 GET 之外的 HTTP 请求的操作。相应地,合约文件中的操作级别代码将如下所示

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

如您在代码中看到的,为了支持通过 jQuery 进行调用,带有值的子属性被标记为 Method=post,因此数据通过 POST 方法发布到服务。

ResponseFormat = WebMessageFormat.Json 指示数据以 JSON 格式返回。

IService.cs

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
     ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

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

步骤 3

您需要更改 Visual Studio 在 Web.Config 文件中为 WCF 服务创建的默认配置,以便它可以与 jQuery 客户端代码发送的 HTTP 协议请求一起使用。

<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" 
        contract="IService" behaviorConfiguration="EndpBehavior"/>
   </service>
  </services>
</system.serviceModel>

如您在上面的配置文件中看到的,EndPoint 设置已更改,并且添加了 EndPointBehaviors 以支持 WEBHTTP 请求。

注意: 配置中完成的 Endpoint 设置与操作的 WebInvoke 属性以及 ServiceType 中设置的兼容性属性结合使用,以支持 jQuery 发送的 HTTP 请求。

步骤 4

要使用 jQuery 使用 Web 服务,即调用 WCF 服务,您可以使用 jQuery.ajax()jQuery.getJSON()。在本文中,我使用了 jQuery.ajax() 方法。

要设置请求,首先定义一个变量。当您调用多个方法并创建一个不同的 *js* 文件来调用 WCF 服务时,这将很有帮助。

<script type="text/javascript">

    var Type;
    var Url;
    var Data;
    var ContentType;
    var DataType;
    var ProcessData;

以下函数初始化上面定义的变量,以便调用服务。

function WCFJSON() {
    var userid = "1";
    Type = "POST";
    Url = "Service.svc/GetUser";
    Data = '{"Id": "' + userid + '"}';
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; varProcessData = true; 
    CallService();
}

CallService 函数通过在 $.ajax 中设置数据来向服务发送请求。

// Function to call WCF  Service       
function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function(msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result) {
    alert('Service call failed: ' + result.status + '' + result.statusText);
    Type = null;
    varUrl = null;
    Data = null; 
    ContentType = null;
    DataType = null;
    ProcessData = null;
}

注意:以下代码检查 result.GetUserResult 语句,因此您的结果对象将获得您的服务方法名称 + Result 属性。 否则,它会给出类似“在 Javascript 中找不到对象”的错误。

function ServiceSucceeded(result) {
    if (DataType == "json") {
        resultObject = result.GetUserResult;
        
        for (i = 0; i < resultObject.length; i++) {
            alert(resultObject[i]);
        }
            
    }
        
}

function ServiceFailed(xhr) {
    alert(xhr.responseText);

    if (xhr.responseText) {
        var err = xhr.responseText;
        if (err)
            error(err);
        else
            error({ Message: "Unknown server error." })
    }
    
    return;
}

$(document).ready(
    function() {
        WCFJSON();
    }
);
</script>

摘要

从您的客户端代码调用 WCF 服务很容易;您只需要将 WCF 服务设置为通过 HTTP 协议提供请求,并将您的客户端设置为通过 HTTP 协议使用它。

© . All rights reserved.