问题
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