Serializing an object with restsharp and passing it to WebApi not serializing list

Diver Dan picture Diver Dan · Sep 4, 2012 · Viewed 38.5k times · Source

I have a a view model that looks like.

public class StoreItemViewModel
{
    public Guid ItemId { get; set; }
    public List<Guid> StoreIds { get; set; }
    [Required]
    public string Description { get; set; }
    //[Required]
    //[DataMember(IsRequired = true)]
    public int ItemTypeId { get; set; }


}

I have a small helper that using is using RestSharp.

public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
    {
        var client = new RestClient(CreateBaseUrl(null))
        {
            Authenticator = new HttpBasicAuthenticator("user", "Password1")
        };

        var request = new RestRequest(apiEndPoint, Method.POST);
        //request.JsonSerializer = new JsonSerializer();
       // {RequestFormat = DataFormat.Json};
        request.AddObject(objectToUpdate);
       // clientJsonSerializer = new YourCustomSerializer();
        var response = client.Execute<T>(request);
        return response;
    }

When debugging the controller within my api

 [HttpPost]
    public HttpResponseMessage Create([FromBody]StoreItemViewModel myProduct)
    {
        //check fields are valid
     .........
     }

myProducts products are all populated apart from the public List StoreIds it always is returning a single reward with an empty Guid. Even if I have added 2 or more StoreIds

I assume this is because I am doing something wrong with my Create helper within my application.

Can anyone help with this its causing a major headache.

The raw data sent to the webapi is looking like

ItemId=f6dbd244-e840-47e1-9d09-53cc64cd87e6&ItemTypeId=6&Description=blabla&StoreIds=d0f36ef4-28be-4d16-a2e8-37030004174a&StoreIds=f6dbd244-e840-47e1-9d09-53cc64cd87e6&StoreId=d0f36ef4-28be-4d16-a2e8-37030004174a

Answer

Paddy picture Paddy · Feb 20, 2015

RestSharp now has a more streamlined way to add an object to the RestRequest Body with Json Serialization:

public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
{
    var client = new RestClient(CreateBaseUrl(null))
    {
        Authenticator = new HttpBasicAuthenticator("user", "Password1")
    };
    var request = new RestRequest(apiEndPoint, Method.POST);
    request.AddJsonBody(objectToUpdate); // HERE
    var response = client.Execute<T>(request);
    return response;
}

This was found in RestSharp 105.0.1.0