简体   繁体   English

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

[英]How to attach payload into RestSharp request?

I can not put a workload in requests with RestSharp. 我无法在使用RestSharp的请求中添加工作负载。 Can anyone help me? 谁能帮我?

I tested 我测试过了

request.AddBody(payload) -> payload is a serialized object in json request.AddBody(payload) - > payload是json中的序列化对象

but, doesn't work for me :/ :/ 但是,对我不起作用:/:/

Thanks a lot :D 非常感谢:D

EDIT - 编辑 -

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; 
} 

The return of method is empty string :/ :/ 方法的返回是空字符串:/:/

I have a helper method that I use: 我有一个帮助方法,我使用:

    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;
    }

With the converter looking like this: 转换器看起来像这样:

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; }
}

I can then call Execute on the returned request. 然后我可以在返回的请求上调用Execute。 I'm wondering whether the serialisation needs to be done by the RestSharp framework (by setting the serialiser to use). 我想知道序列化是否需要由RestSharp框架完成(通过设置序列化器来使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM