我要建一个RESTful API客户端在C#.NET 3.5。
I'm building a RESTful API client in C# .NET 3.5.
我第一次开始与构建它的好老 HttpWebClient
(和 HttpWebResponse
),我可以做任何我想要的用。我很高兴。我被困在唯一的事是从JSON响应自动反序列化。
I first started building it with the good old HttpWebClient
(and HttpWebResponse
), I could do whatever I wanted with. I were happy. The only thing I was stuck on was the automatic deserialization from JSON response.
所以,我听说过一个美妙的库称为RestSharp(104.1),从而简化了REST的API客户端的发展,并自动反序列化JSON和XML响应。我打开这一切我的code,但现在我知道,我不能做的事情我可以做 HttpWebClient
和 HttpWebResponse
,如访问和编辑的原始请求主体。
So, I've heard about a wonderful library called RestSharp (104.1) which eases the development of RESTful API clients, and automatically deserialize JSON and XML responses. I switched all my code on it, but now I realize I can't do things I could do with HttpWebClient
and HttpWebResponse
, like access and edit the raw request body.
任何人有一个解决方案?
Anyone has a solution ?
编辑:我知道如何设置请求主体(以 request.AddBody()
),我的问题是,我想这个请求体中的字符串,编辑它,并重新设置请求(更新请求体上飞)
Edit : I know how to set the request body (with request.AddBody()
), my problem is that I want to get this request body string , edit it, and re-set it in the request (updating the request body on the fly)
请求的身体是一种类型的参数。要添加一个,你可以做其中的一个......
The request body is a type of parameter. To add one, you can do one of these...
req.AddBody(body);
req.AddBody(body, xmlNamespace);
req.AddParameter("text/xml", body, ParameterType.RequestBody);
req.AddParameter("application/json", body, ParameterType.RequestBody);
要取回身体参数,你可以看看在 req.Parameters
藏品,其中键入
等于以 ParameterType.RequestBody
。
To retrieve the body parameter you can look for items in the req.Parameters
collection where the Type
is equal to ParameterType.RequestBody
.
请参阅code为 RestRequest
类的这里。
See code for the RestRequest
class here.
下面是关于 ParameterType.RequestBody 不得不说:
Here is what the RestSharp docs on ParameterType.RequestBody
has to say:
如果该参数设置,它的值将作为的身体 请求。参数的名称被忽略,所以是附加 RequestBody参数 - 只有1个被接受
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只能在POST或PUT请求,因为他们实际上只 送一具尸体。
RequestBody only works on POST or PUT Requests, as only they actually send a body.
如果您有GetOrPost参数,以及,他们将覆盖 RequestBody - RestSharp不会将它们结合起来,但是这反而 扔RequestBody参数了。
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.
有关读取/上即时更新的身体参数,你可以试试:
For reading/updating the body parameter on-the-fly, you can try:
var body = req.Parameters.Where(p => p.Type == ParameterType.RequestBody).FirstOrDefault();
if (body != null)
{
Console.WriteLine("CurrentBody={0}", body.Value);
body.Value = "NewBodyValue";
}
要是做不到这一点,创建 RestRequest
对象的新副本,不同的身体。
Or failing that, create a new copy of the RestRequest
object with a different body.