如何在 RestSharp 中向请求正文添加文本
我正在尝试使用 RestSharp 来使用 Web 服务。到目前为止,一切进展顺利(为 John Sheehan 和所有贡献者干杯!),但我遇到了障碍。假设我想将 XML 以已序列化的形式(即作为字符串)插入到 RestRequest 的正文中。有没有简单的方法可以做到这一点?看来 .AddBody() 函数在幕后进行序列化,因此我的字符串被转换为
。
非常感谢任何帮助!
编辑:请求提供我当前代码的示例。见下文 -
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;
}
I'm trying to use RestSharp to consume a web service. So far everything's gone very well (cheers to John Sheehan and all contributors!) but I've run into a snag. Say I want to insert XML into the body of my RestRequest in its already serialized form (i.e., as a string). Is there an easy way to do this? It appears the .AddBody() function conducts serialization behinds the scenes, so my string is being turned into <String />
.
Any help is greatly appreciated!
EDIT: A sample of my current code was requested. See below --
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是如何将纯 xml 字符串添加到请求正文中:
req.AddParameter("text/xml", body, ParameterType.RequestBody)
;Here is how to add plain xml string to the request body:
req.AddParameter("text/xml", body, ParameterType.RequestBody)
;要添加到@dmitreyg的答案以及@jrahhali对其答案的评论,在当前版本中,截至发布时它是
v105.2.3
,语法如下: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: