如何在 RestSharp 中向请求体添加文本

我正在尝试使用 RestSharp 来使用 Web 服务。到目前为止,一切进展顺利(为约翰 · 希恩和所有贡献者干杯!)但我遇到麻烦了。假设我想以已经序列化的形式(例如,作为字符串)将 XML 插入 RestRequest 的主体。有什么简单的方法吗?看起来。函数在后台进行序列化,所以我的字符串被转换成了 <String />

非常感谢您的帮助!

编辑: 请求提供我当前代码的一个示例

private T ExecuteRequest<T>(string resource,
RestSharp.Method httpMethod,
IEnumerable<Parameter> parameters = null,
string body = null) where T : new()
{
RestClient client = new RestClient(this.BaseURL);
RestRequest req = new RestRequest(resource, httpMethod);


// Add all parameters (and body, if applicable) to the request
req.AddParameter("api_key", this.APIKey);
if (parameters != null)
{
foreach (Parameter p in parameters) req.AddParameter(p);
}


if (!string.IsNullOrEmpty(body)) req.AddBody(body); // <-- ISSUE HERE


RestResponse<T> resp = client.Execute<T>(req);
return resp.Data;
}
80709 次浏览

以下是如何将纯 xml 字符串添加到请求主体:

req.AddParameter("text/xml", body, ParameterType.RequestBody);

To Add to @dmitreyg's answer and per @jrahhali's comment to his answer, in the current version, as of the time this is posted it is v105.2.3, the syntax is as follows:

request.Parameters.Add(new Parameter() {
ContentType = "application/json",
Name = "JSONPAYLOAD", // not required
Type = ParameterType.RequestBody,
Value = jsonBody
});


request.Parameters.Add(new Parameter() {
ContentType = "text/xml",
Name = "XMLPAYLOAD", // not required
Type = ParameterType.RequestBody,
Value = xmlBody
});