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

前端 未结 3 900
傲寒
傲寒 2021-02-07 20:29

I have a a view model that looks like.

public class StoreItemViewModel
{
    public Guid ItemId { get; set; }
    public List StoreIds { get; set; }
         


        
相关标签:
3条回答
  • 2021-02-07 21:06

    I managed to get this working. I don't think its the correct way but it works.

     public static IRestResponse Create<T>(object objectToUpdate, string apiEndPoint) where T : new()
        {
            var client = new RestClient(CreateBaseUrl(null))
            {
                Authenticator = new HttpBasicAuthenticator("user", "Password1")
            };
            var json = JsonConvert.SerializeObject(objectToUpdate);
            var request = new RestRequest(apiEndPoint, Method.POST);
            request.AddParameter("text/json", json, ParameterType.RequestBody);
            var response = client.Execute<T>(request);
            return response;
        }
    
    0 讨论(0)
  • 2021-02-07 21:06

    I struggled with the same problem and came up a working solution.

    1. Be sure to set the request format to JSON:

      request.RequestFormat = DataFormat.Json;

    2. Use AddBody, rather than AddObject:

      request.AddBody(zNewSessionUsage);

    So your code would be something like this:

    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.RequestFormat = DataFormat.Json;
        request.AddBody(objectToUpdate);
        var response = client.Execute<T>(request);
        return response;
    }
    
    0 讨论(0)
  • 2021-02-07 21:08

    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

    0 讨论(0)
提交回复
热议问题