2

我无法使用 RestSharp 将工作量放入请求中。谁能帮我?

我测试过

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

但是,对我不起作用:

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

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

4

2 回答 2

5

我有一个我使用的辅助方法:

    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 框架完成(通过设置要使用的序列化程序)。

于 2013-05-07T10:13:33.700 回答
0

Restsharp 版本105.0添加了一个新方法IRestRequest.AddJsonBody,所以现在你只需要调用AddJsonBody()它会为你做剩下的事情:

request.AddJsonBody(new MyParam
{
   IntData = 1,
   StringData = "test123"
});
于 2021-08-13T10:16:53.620 回答