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

Grz*_*nio 11 .net c# wcf json web-services

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

Cod*_*odo 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);
}
Run Code Online (Sandbox Code Playgroud)

服务数据结构

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

    [DataMember]
    public string Make { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

服务实施

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

服务标记

<%@ ServiceHost Language="C#" Service="JSONService.Service1"
    CodeBehind="Service1.svc.cs"
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

客户

而现在是客户.它重用了接口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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

玩得开心.

  • 你确实意识到它不是REST,对吗?RPC over HTTP可能很有价值,但它不会实现REST架构带来的好处. (4认同)

Mik*_*e_G -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
    });
}
Run Code Online (Sandbox Code Playgroud)

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

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