首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在RestSharp中向请求正文添加文本

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

Stack Overflow用户
提问于 2011-02-24 02:58:45
回答 2查看 72.5K关注 0票数 110

我正在尝试使用RestSharp来使用web服务。到目前为止,一切都很顺利(为John Sheehan和所有贡献者干杯!)但我遇到了一个小麻烦。假设我想以已经序列化的形式(即字符串)将XML插入到RestRequest的主体中。有什么简单的方法可以做到这一点吗?看起来.AddBody()函数在场景后面执行序列化,所以我的字符串被转换为<String />

任何帮助都是非常感谢的!

编辑:我当前的代码样本已被请求。见下文--

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-22 23:28:07

下面是如何将纯xml字符串添加到请求正文中:

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

票数 230
EN

Stack Overflow用户

发布于 2017-06-30 04:14:14

为了补充@dmitreyg的答案和per @jrahhali对他的答案的评论,在当前版本中,截至本文发布时为v105.2.3,语法如下:

代码语言:javascript
复制
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
});
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5095692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档