Pass multiple complex objects to a post/put Web API method

后端 未结 11 1442
南旧
南旧 2020-11-29 21:51

Can some please help me to know how to pass multiple objects from a C# console app to Web API controller as shown below?

using (var httpClient = new System.N         


        
11条回答
  •  时光取名叫无心
    2020-11-29 22:24

    Basically you can send complex object without doing any extra fancy thing. Or without making changes to Web-Api. I mean why would we have to make changes to Web-Api, while the fault is in our code that's calling the Web-Api.

    All you have to do use NewtonSoft's Json library as following.

    string jsonObjectA = JsonConvert.SerializeObject(objectA);
    string jsonObjectB = JsonConvert.SerializeObject(objectB);
    string jSoNToPost = string.Format("\"content\": {0},\"config\":\"{1}\"",jsonObjectA , jsonObjectB );
    //wrap it around in object container notation
    jSoNToPost = string.Concat("{", jSoNToPost , "}"); 
    //convert it to JSON acceptible content
    HttpContent content = new StringContent(jSoNToPost , Encoding.UTF8, "application/json"); 
    
    var response = httpClient.PutAsync("api/process/StartProcessiong", content);
    

提交回复
热议问题