سؤال

I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.

I have been using RestSharp to call API.

Code Implemenation:

  var client = new RestClient(BaseUrl);
  var request = new RestRequest(ResourceUrl, Method.POST);
  IDictionary<string,string> dicRequeset = new Dictionary<string, string>
                {
                    {"request-id", "1234"},
                    {"hardware-id", "CCCCXXX"},
                };
  request.AddParameter("request", dicRequeset);
  var response = client.Execute(request);
  var content = response.Content;

PHP API Implementation(Short):

 * Expected input:
 *   string request[request-id,hardware-id]
 * Return:
 *   code = 0 for success
 *   string activation_code
 */
function activate()
    {
        $license = $this->checkFetchLicense();
        if (!$license instanceof License) return;

        $response = $license->activate((array)$this->_request->getParam('request'));
    }

Can someone help me to pass array to PHP API from C#?

هل كانت مفيدة؟

المحلول 2

Though late post but I've solved this problem by using following approach :

        var request = new RestRequest(ResourceUrl, Method.POST);
        request.AddParameter("request[request-id]", hardwareId);
        request.AddParameter("request[hardware-id]", hardwareId);

نصائح أخرى

Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?

IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234"); 
dicRequeset.Add("hardware-id", "CCCCXXX");

Or using indexer?

dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";

Or the best I can imagine is JSON as it is designed for the purpose of transmission.

var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});

The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.

if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method. So try to get a JSON.net library and make the json encoding manually,

IDictionary<string,string> dicRequeset = new Dictionary<string, string>
                {
                    {"request-id", "1234"},
                    {"hardware-id", "CCCCXXX"},
                };
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);

this should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top