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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5095692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:18:45  来源:igfitidea点击:

How to add text to request body in RestSharp

.netxmlrestsharp

提问by Matt G.

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 />.

我正在尝试使用 RestSharp 来使用 Web 服务。到目前为止,一切都进展顺利(为 John Sheehan 和所有贡献者干杯!)但我遇到了一个障碍。假设我想以已经序列化的形式(即,作为字符串)将 XML 插入到我的 RestRequest 的正文中。是否有捷径可寻?看来 .AddBody() 函数在幕后进行序列化,所以我的字符串正在变成<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;
}

回答by dmitreyg

Here is how to add plain xml string to the request body:

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

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

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

回答by interesting-name-here

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:

要添加到@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
});