[英]Send JSON data to REST API with sub payloads
I am trying to send JSON data to a REST API using my C# application 我正在尝试使用C#应用程序将JSON数据发送到REST API
The JSON data should be like that: JSON数据应如下所示:
{
'agent': {
'name': 'AgentHere',
'version': 1
},
'username': 'Auth',
'password': 'Auth'
}
So, as you can see... agent
have sub payloads which are name
and version
因此,如您所见... agent
具有子有效载荷,即name
和version
I am calling the REST API using RestSharp like that: 我正在使用RestSharp调用REST API,如下所示:
var client = new RestClient("https://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest(Method.POST);
request.AddParameter(
"{'agent': { 'name': 'AgentHere', 'version': 1 }, 'username': 'Auth', 'password': 'Auth' }"
);
// easily add HTTP Headers
request.AddHeader("Content-Type", "application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
But I get the errors The best overloaded method match for 'RestSharp.RestRequest.AddParameter(RestSharp.Parameter)' has some invalid arguments
and Argument 1: cannot convert from 'string' to 'RestSharp.Parameter'
on this line: 但是我得到了错误The best overloaded method match for 'RestSharp.RestRequest.AddParameter(RestSharp.Parameter)' has some invalid arguments
并且Argument 1: cannot convert from 'string' to 'RestSharp.Parameter'
在此行Argument 1: cannot convert from 'string' to 'RestSharp.Parameter'
:
request.AddParameter(
"{'agent': { 'name': 'AgentHere', 'version': 1 }, 'username': 'Auth', 'password': 'Auth' }"
);
I am unable to make the sub payload 我无法使子有效载荷
Any help would be appreciated. 任何帮助,将不胜感激。
Thanks! 谢谢!
It appears that data is meant for the request body. 数据似乎是为请求正文提供的。 Use the appropriate AddParameter
overload. 使用适当的AddParameter
重载。
var request = new RestRequest(Method.POST);
var contentType = "application/json";
var bodyData = "{\"agent\": { \"name\": \"AgentHere\", \"version\": 1 }, \"username\": \"Auth\", \"password\": \"Auth\" }";
request.AddParameter(contentType, bodyData, ParameterType.RequestBody);
To avoid constructing the JSON manually, which can lead to errors, use the AddJsonBody()
with an object representing the data to serialize 为了避免手动构造JSON(这可能导致错误),请使用AddJsonBody()
和表示要序列化的数据的对象
var request = new RestRequest(Method.POST);
var data = new {
agent = new {
name = "AgentHere",
version = 1
},
username = "Auth",
password = "Auth"
};
//Serializes obj to JSON format and adds it to the request body.
request.AddJsonBody(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.