How to call an API which is based on XML-RPC specification in C#?

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-14 22:55:48

问题


Here is my sample request,

<?xml version=”1.0” encoding=”UTF-8”?>
 <methodCall>
  <methodName>login</methodName>
   <params>
    <param>
     <value>
      <struct>
       <member>
        <name>password</name>
        <value><string>XXXXXXXXXX</string></value>
       </member>
       <member>
        <name>username</name>
        <value><string>XXXX@XXX.com</string></value>
       </member>
    </struct>
  </value>
 </param>
 </params>
</methodCall>

Here is my sample successful response for the request:

<struct>
  <member>
    <name>id</name>
    <value><string>12345</string></value>
  </member>
  <member>
    <name>api_status</name>
    <value><int>200</int></value>
  </member>
</struct>

Question:

I was trying to call an API endpoint from a .NET console application. But, it didn't get connected to the server. Can anyone tell me how can I call this API endpoint using C#?


回答1:


Step 1 : Created a Console Application in .NET

Step 2 : Install the NuGet "xml-rpc.net"

Step 3: Created a sample request model class like this,

 public class request
    {
        public string username { get; set; }
        public string password { get; set; }
    }

Step 4 : Created a sample response model class like this,

public class response
    {
        public int id { get; set; }
        public int status { get; set; }        
    }

Step 5 : Create an interface which is inherited form IXmlRpcProxy base class with the help of the namespace using CookComputing.XmlRpc; and this interface must contain our endpoint method and it should decorate with the filter XmlRpcUrl having the API resource.

    [XmlRpcUrl("https://api.XXX.com/XXX")]
    public interface FlRPC : IXmlRpcProxy
    {
        [XmlRpcMethod("login")]//endpoint name
        response login(request request);
    }

Step 6 : To make calls to an XML-RPC server it is necessary to use an instance of a proxy class.

class Program
    {
        static void Main(string[] args)
        {
            response response = new response();
            request request = new request();
            FlRPC proxy = XmlRpcProxyGen.Create<FlRPC>();
            request.password = "xxxxxxxx";
            request.username = "xxxx@xxxx.org";
            response = proxy.login(request);
        }
    }

Note: The above request, response model class must contain all the properties and the property name should be slimier to the payload of the endpoint's request, response.



来源:https://stackoverflow.com/questions/40647779/how-to-call-an-api-which-is-based-on-xml-rpc-specification-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!