.net 如何在c# whmcs中传递自定义字段

w1jd8yoj  于 2023-01-27  发布在  .NET
关注(0)|答案(1)|浏览(116)

我想在add order API中添加自定义字段。如何创建这样的数组:“产品自定义字段值的base64编码序列化数组的数组”
https://developers.whmcs.com/api-reference/addorder/
我试过了

Dictionary<string, string> customfiled = new Dictionary<string, string>();

customfiled.Add("1", "Hello");

var tt2 = JsonConvert.SerializeObject(customfiled);
  
string str =Base64Encode(tt2);
kh212irz

kh212irz1#

我创建了一个类,它将保存序列化为JSON的键/值列表。
下面是课程:

class ArrayOfBase64Array
{
    // serialized JSON 
    private List<string> list = new List<string>();
        
    public void Add(NameValueCollection collection) 
    {
        foreach(var key in collection.AllKeys)
        {
           this.Add(key, collection[key]);
        }
    }

    public void Add<T>(string key, T value) {
        var dict = new Dictionary<string,T>();
        dict.Add(key, value);
        var json = JsonConvert.SerializeObject(dict);
        list.Add(Base64Encode(json));
    }
    
    public string[] ToArray() 
    {
        return list.ToArray();
    }
    
    string Base64Encode(string value) 
    {
      return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
    }
}

AddOrder有效负载需要与此C#类匹配的形状:

// lots of fields omitted for brevity
class AddOrder
{
    public string   action {get;set;}      
    public string[] domain {get;set;}  
    public string[] customfields {get;set;}
}

要创建具有自定义字段的AddOrder示例,您现在可以执行以下操作:

// create an AddOrder instance
   var addOrder = new AddOrder 
   { 
      action = "AddOrder",
      domain = new [] {"one.example.com", "two.example.com"} 
   };
   
   // build our customfields collection
   var cfarray = new ArrayOfBase64Array();
   cfarray.Add("1", "FuBar");
   cfarray.Add("2", 999);
   cfarray.Add("3", true);
   cfarray.Add("4", new JObject(new JProperty("Foo", 4711.42)));
   
   // or if you have a namevaluecollection
   var nvc = new NameValueCollection { {"5", "test namevalue 1"}, {"6", "another value"} };
   cfarray.Add(nvc);

   // store the customfields as an array of strings
   addOrder.customfields = cfarray.ToArray();

以下是数据在POST到服务器时的外观:

{ "action":"AddOrder",
    "domain":["one.example.com","two.example.com"],
    "customfields":[
       "eyIxIjoiRnVCYXIifQ==",
       "eyIyIjo5OTl9",
       "eyIzIjp0cnVlfQ==",
       "eyI0Ijp7IkZvbyI6NDcxMS40Mn19",   
       "eyI1IjoidGVzdCBuYW1ldmFsdWUgMSJ9",
       "eyI2IjoiYW5vdGhlciB2YWx1ZSJ9"]
  }

这就是每一个base64编码字符串的内容:

{"1":"FuBar"}
{"2":999}
{"3":true}
{"4":{"Foo":4711.42}}
{"5":"test namevalue 1"}
{"6":"another value"}

相关问题