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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/835839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:33:10  来源:igfitidea点击:

Client configuration to consume WCF JSON web service

c#.netwcfweb-servicesjson

提问by Grzenio

I have configured the web service to use Json as described on this blog: http://www.west-wind.com/weblog/posts/164419.aspxand various other blogs, but I couldn't create a client to consume this service. I tried various things, but invariably I got meaningless exceptions. What is the correct way to implement the (WCF I should add) client?

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

回答by Mike_G

What are the exceptions? They may be meaningless to you, but some one around here might find them helpful in diagnosing your problem. I use jQuery to make ajax request to a WCF service and the settup usually looks like this:

有哪些例外?它们对您来说可能毫无意义,但这里的某些人可能会发现它们有助于诊断您的问题。我使用 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
    });
}

The JSON.stringify() can be found in the json.org script: http://www.json.org/js.html, and my sig for GetData method looks like this:

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);

回答by Codo

There seems to be a shortage of examples about how to write a WCF client for a JSON REST service. Everybody seems to use WCF for implementing the service but hardly ever for writing a client. So here's a rather complete example of the service (implementing a GET and a POST request) and the client.

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

Service

服务

Service interface

服务接口

[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);
}

Service data structures

服务数据结构

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

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

Service implementation

服务实现

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;
    }
}

Service markup

服务标记

<%@ 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>

Client

客户

And now the client. It reuses the interface IService1and the class Car. In addition, the following code and configuration is required.

现在是客户端。它重用了接口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

程序.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);
    }
}

Have fun.

玩得开心。