如何将有效负载附加到RestSharp请求中?

时间:2013-05-07 07:16:56

标签: c# request oauth-2.0 restsharp payload

我无法在使用RestSharp的请求中添加工作负载。任何人都可以帮助我吗?

我测试了

request.AddBody(payload) - > payload是json中的序列化对象

但是,对我不起作用:/:/

非常感谢:D

编辑 -

public override string Post(string url, object payload) { 
    RestRequest request = new RestRequest(url, Method.POST); 
    request.RequestFormat = DataFormat.Json;
    request.AddBody(payload); 
    IRestResponse response = Client.Execute(request); 
    return response.Content; 
} 

方法的返回是空字符串:/:/

1 个答案:

答案 0 :(得分:4)

我使用了一个帮助方法:

    private IRestRequest CreateRequest(Uri uri, Method method, object body)
    {
        IRestRequest request = new RestRequest(uri, method);
        request.Resource = uri.ToString();
        request.Timeout = _timeout;

        if (body != null)
        {
            request.AddHeader("Content-Type", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.JsonSerializer = new CustomConverter {ContentType = "application/json"};
            request.AddBody(body);
        }

        return request;
    }

转换器看起来像这样:

class CustomConverter : ISerializer, IDeserializer
{
    private static readonly JsonSerializerSettings SerializerSettings;

    static CustomConverter ()
    {
        SerializerSettings = new JsonSerializerSettings
        {
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            Converters = new List<JsonConverter> { new IsoDateTimeConverter() },
            NullValueHandling = NullValueHandling.Ignore
        };
    }

    public string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj, Formatting.None, SerializerSettings);
    }

    public T Deserialize<T>(IRestResponse response)
    {
        var type = typeof(T);

        return (T)JsonConvert.DeserializeObject(response.Content, type, SerializerSettings);
    }

    string IDeserializer.RootElement { get; set; }
    string IDeserializer.Namespace { get; set; }
    string IDeserializer.DateFormat { get; set; }
    string ISerializer.RootElement { get; set; }
    string ISerializer.Namespace { get; set; }
    string ISerializer.DateFormat { get; set; }
    public string ContentType { get; set; }
}

然后我可以在返回的请求上调用Execute。我想知道序列化是否需要由RestSharp框架完成(通过设置序列化器来使用)。