教程:简单的WCF XML-RPC客户端

时间:2010-05-20 22:54:10

标签: c# wcf client xml-rpc

更新:我在下面的回答中提供了完整的代码示例。

我已经构建了自己的小型自定义XML-RPC服务器,因为我想在服务器端和客户端都保持简单,我想要完成的是创建一个最简单的客户端(在C#中最好)使用WCF。

假设通过XML-RPC公开的服务合同如下:

[ServiceContract]
public interface IContract
{
    [OperationContract(Action="Ping")]
    string Ping(); // server returns back string "Pong"

    [OperationContract(Action="Echo")]
    string Echo(string message); // server echoes back whatever message is
}

因此,有两个示例方法,一个没有任何参数,另一个带有简单的字符串参数,两个都返回字符串(仅为了示例)。服务通过http。

公开

Aaand,下一步是什么? :)

2 个答案:

答案 0 :(得分:13)

受到Doobi答案的启发,我查阅了有关该主题的更多信息(示例),并得出以下结论。

创建简单WCF XML-RPC客户端的步骤:

  1. 从此页面下载WCF的XML-RPC:http://vasters.com/clemensv/PermaLink,guid,679ca50b-c907-4831-81c4-369ef7b85839.aspx(下载链接位于页面顶部)
  2. 创建一个以 .NET 4.0完整框架为目标的空项目(否则稍后将无法使用System.ServiceModel.Web)
  3. Microsoft.Samples.XmlRpc 项目从存档添加到您的项目中
  4. 添加对Microsoft.Samples.XmlRpc项目的引用
  5. 添加对System.ServiceModel和System.ServiceModel.Web
  6. 的引用

    示例代码

    using System;
    using System.ServiceModel;
    using Microsoft.Samples.XmlRpc;
    
    namespace ConsoleApplication1
    {
    
    
        // describe your service's interface here
        [ServiceContract]
        public interface IServiceContract
        {
            [OperationContract(Action="Hello")]
            string Hello(string name);
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                ChannelFactory<IServiceContract> cf = new ChannelFactory<IServiceContract>(
                    new WebHttpBinding(), "http://www.example.com/xmlrpc");
    
                cf.Endpoint.Behaviors.Add(new XmlRpcEndpointBehavior());
    
                IServiceContract client = cf.CreateChannel();
    
                // you can now call methods from your remote service
                string answer = client.Hello("World");
            }
        }
    }
    

    示例请求/响应消息

    请求XML

    <?xml version="1.0" encoding="utf-8"?>
    <methodCall> 
        <methodName>Hello</methodName> 
        <params> 
            <param> 
                <value> 
                    <string>World</string> 
                </value> 
            </param> 
        </params> 
    </methodCall> 
    

    响应XML

    <?xml version="1.0" encoding="utf-8"?>
    <methodResponse> 
        <params> 
            <param> 
                <value> 
                    <string>Hello, World!</string> 
                </value> 
            </param> 
        </params> 
    </methodResponse> 
    

答案 1 :(得分:6)

最简单的方法是使用WCF channelfactory

    IStuffService client = new ChannelFactory<IStuffService>(
        new BasicHttpBinding(),
        *"Stick service URL here"*)
        .CreateChannel();

只需调用

即可执行请求
var response = client.YourOperation(params)

此处有更多详情: http://msdn.microsoft.com/en-us/library/ms734681.aspx

编辑:编辑;)