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

时间:2011-02-23 18:58:45

标签: .net xml restsharp

我正在尝试使用RestSharp来使用Web服务。到目前为止,一切都进行得很顺利(为约翰希恩和所有贡献者欢呼!)但我遇到了麻烦。假设我想以已经序列化的形式(即,作为字符串)将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;
}

2 个答案:

答案 0 :(得分:190)

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

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

答案 1 :(得分:5)

要添加到@ dmitreyg的答案,并根据@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
});