c# - 如何使用 RestSharp 访问 HTTP 请求体?

标签 c# rest .net-3.5 client restsharp

我正在使用 C# .NET 3.5 构建一个 RESTful API 客户端。

我首先使用良好的旧HttpWebClient(和HttpWebResponse)开始构建它,我可以做任何我想做的事。我很高兴。我唯一坚持的是 JSON 响应的自动反序列化。

所以,我听说过一个很棒的库,叫做 RestSharp (104.1),它简化了 RESTful API 客户端的开发,并自动反序列化 JSON 和 XML 响应。我在上面切换了我的所有代码,但现在我意识到我不能做我可以用 HttpWebClientHttpWebResponse 做的事情,比如访问和编辑原始请求正文。

谁有解决办法?

编辑:我知道如何设置请求主体(使用 request.AddBody()),我的问题是我想获取此请求主体字符串,编辑它,然后重新- 在请求中设置它(即时更新请求正文)

最佳答案

请求体是一种参数。要添加一个,您可以执行以下操作之一...

req.AddBody(body);
req.AddBody(body, xmlNamespace);
req.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);

要检索正文参数,您可以在 req.Parameters 集合中查找项目,其中 Type 等于 ParameterType.RequestBody

查看 RestRequest 类的代码 here .

这是 RestSharp docs on ParameterType.RequestBody 的内容不得不说:

If this parameter is set, it’s value will be sent as the body of the request. The name of the Parameter is ignored, and so are additional RequestBody Parameters – only 1 is accepted.

RequestBody only works on POST or PUT Requests, as only they actually send a body.

If you have GetOrPost parameters as well, they will overwrite the RequestBody – RestSharp will not combine them but it will instead throw the RequestBody parameter away.

要即时读取/更新主体参数,您可以尝试:

var body = req.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
if (body != null)
{
    Console.WriteLine("CurrentBody={0}", body.Value);
    body.Value = "NewBodyValue";
}

或者做不到这一点,创建一个具有不同主体的 RestRequest 对象的新副本。

关于c# - 如何使用 RestSharp 访问 HTTP 请求体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16768314/

相关文章:

c# - 可以ping通网络设备但没有tcp连接

php - 多部分请求时 Fosrestbundle 主体为空

java - Apache Camel 根据请求使用文件内容丰富消息

wcf - 如何从 .NET 客户端应用程序进入 WCF Rest 服务?

c# - 我的程序集实际运行的是哪个版本的 .Net 框架?

c# - 在 C# 构造函数中强制显式初始化成员

c# - 测试项目数组是否在预定义数组中的最佳方法是什么

c# - NHibernate 除了存储过程什么都没有

c# - 从内存流播放视频

c# - 从其他类更新 UI 的最佳方式?