我无法使用 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;
}
方法返回空字符串:/:/
我有一个我使用的辅助方法:
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 框架完成(通过设置要使用的序列化程序)。
我是一名优秀的程序员,十分优秀!