gpt4 book ai didi

c# - 如何将 json 格式的有效负载附加到 RestSharp 请求中?

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:05 26 4
gpt4 key购买 nike

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

关于c# - 如何将 json 格式的有效负载附加到 RestSharp 请求中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16413334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com