客户端配置以使用WCF JSON Web服务

时间:2009-05-07 16:51:28

标签: c# .net wcf web-services json

我已将Web服务配置为使用此博客中描述的Json:http://www.west-wind.com/weblog/posts/164419.aspx和其他各种博客,但我无法创建客户端来使用此服务。我尝试了各种各样的东西,但总是有无意义的例外。实现(我应该添加的WCF)客户端的正确方法是什么?

2 个答案:

答案 0 :(得分:43)

似乎缺少关于如何为JSON REST服务编写WCF客户端的示例。每个人似乎都使用WCF来实现服务,但几乎没有用于编写客户端。所以这是一个相当完整的服务示例(实现GET和POST请求)和客户端。

服务

服务界面

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/getcar/{id}")]
    Car GetCar(string id);

    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/updatecar/{id}")]
    Car UpdateCar(string id, Car car);
}

服务数据结构

[DataContract]
public class Car
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string Make { get; set; }
}

服务实施

public class Service1 : IService1
{
    public Car GetCar(string id)
    {
        return new Car { ID = int.Parse(id), Make = "Porsche" };
    }

    public Car UpdateCar(string f, Car car)
    {
        return car;
    }
}

服务标记

<%@ ServiceHost Language="C#" Service="JSONService.Service1"
    CodeBehind="Service1.svc.cs"
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

<强>的Web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>   
</configuration>

客户端

现在是客户。它重用了接口IService1和类Car。此外,还需要以下代码和配置。

<强>的App.config

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webby">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <client>
      <endpoint address="http://localhost:57211/Service1.svc" name="Service1" binding="webHttpBinding" contract="JSONService.IService1" behaviorConfiguration="webby"/>
    </client>
  </system.serviceModel>
</configuration>

<强> Program.cs的

public class Service1Client : ClientBase<IService1>, IService1
{
    public Car GetCar(string id)
    {
        return base.Channel.GetCar(id);
    }


    public Car UpdateCar(string id, Car car)
    {
        return base.Channel.UpdateCar(id, car);
    }
}


class Program
{
    static void Main(string[] args)
    {
        Service1Client client = new Service1Client();
        Car car = client.GetCar("1");
        car.Make = "Ferrari";
        car = client.UpdateCar("1", car);
    }
}

玩得开心。

答案 1 :(得分:-1)

有什么例外?它们对你来说可能毫无意义,但是这里的某些人可能会发现它们对诊断你的问题很有帮助。我使用jQuery向WCF服务发出ajax请求,并且设置通常如下所示:

     $(document).ready(function() {

        $.ajaxSetup({
            type: "POST",
            processData: true,
            contentType: "application/json",
            timeout: 5000,
            dataType: "json"
        });
        var data = { "value": 5 };

        AjaxPost("GetData", data, OnEndGetData, OnError);
    });

    function OnEndGetData(result) {
        alert(result.GetDataResult);
    }

    function OnError(msg) {
        alert(msg);
    }

function AjaxPost(method, data, callback, error) {
    var stringData = JSON.stringify(data);
    var url = "Service1.svc/" + method;

    $.ajax({
        url: url,
        data: stringData,
        success: function(msg) {
            callback(msg);
        },
        error: error
    });
}

JSON.stringify()可以在json.org脚本中找到:http://www.json.org/js.html,我的GetData方法的sig如下所示:

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