我正在尝试使用RestSharp来使用web服务。到目前为止,一切都很顺利(为John Sheehan和所有贡献者干杯!)但我遇到了一个小麻烦。假设我想以已经序列化的形式(即字符串)将XML插入到RestRequest的主体中。有什么简单的方法可以做到这一点吗?看起来.AddBody()函数在场景后面执行序列化,所以我的字符串被转换为<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;
}
发布于 2011-03-22 23:28:07
下面是如何将纯xml字符串添加到请求正文中:
req.AddParameter("text/xml", body, ParameterType.RequestBody)
;
发布于 2017-06-30 04:14:14
为了补充@dmitreyg的答案和per @jrahhali对他的答案的评论,在当前版本中,截至本文发布时为v105.2.3
,语法如下:
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
});
https://stackoverflow.com/questions/5095692
复制相似问题