Can RestSharp send a List<string> in a POST request?

血红的双手。 提交于 2019-12-05 19:34:48

问题


I am trying to get RestSharp to work with a restful service that I have. Everything seems to be working fine, except when my object being passed via POST contains a list (in this particular case a list of string).

My object:

public class TestObj
{
    public string Name{get;set;}
    public List<string> Children{get;set;}
}

When this gets sent to the server the Children property gets sent as a string with the contents System.Collections.Generic.List`1[System.String].

This is how I am sending the object:

var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);

var test = new TestObj {Name = "Fred", Children = new List<string> {"Arthur", "Betty"}};
request.AddObject(test);
client.Execute<TestObj>(request);

Am I doing something wrong, or is this a bug in RestSharp? (If it makes a difference, I am using JSON, not XML.)


回答1:


It depends on what server you're hitting, but if you're hitting an ASP.NET Web API controller (and probably other server-side technologies), it'll work if you add each item in the collection in a loop:

foreach (var child in test.Children) 
    request.AddParameter("children", x));



回答2:


I had a similar problem with a list of Guids. My post would work but the list would never have the correct data. I hacked it abit and used the json.net to serialize the object

Issue I had on another stackoverflow post

I know this isn't perfect but does the trick




回答3:


Use AddJsonBody

var client = new RestClient();
var request = new RestRequest("http://localhost", Method.PUT);
request.AddJsonBody(new TestObj {
     Name = "Fred", 
     Children = new List<string> {"Arthur", "Betty"}
});
client.Execute(request);

Api Side

[AcceptVerbs("PUT")]
string Portefeuille(TestObj obj)
{
    return String.Format("Sup' {0}, you have {1} nice children", 
        obj.Name, obj.Children.Count());
}


来源:https://stackoverflow.com/questions/12284931/can-restsharp-send-a-liststring-in-a-post-request

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