C# 使用子有效负载将JSON数据发送到REST API
我试图使用我的C#应用程序将JSON数据发送到RESTAPI JSON数据应该如下所示:C# 使用子有效负载将JSON数据发送到REST API,c#,json,restsharp,C#,Json,Restsharp,我试图使用我的C#应用程序将JSON数据发送到RESTAPI JSON数据应该如下所示: { 'agent': { 'name': 'AgentHere', 'version': 1 }, 'username': 'Auth', 'password': 'Auth' } var client = new RestClient("https://example.com"); // client.Authent
{
'agent': {
'name': 'AgentHere',
'version': 1
},
'username': 'Auth',
'password': 'Auth'
}
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
所以,正如你所看到的<代码>代理具有子有效载荷,这些子有效载荷是名称
和版本
我使用RestSharp调用RESTAPI,如下所示:
{
'agent': {
'name': 'AgentHere',
'version': 1
},
'username': 'Auth',
'password': 'Auth'
}
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
但是我得到的错误是,与'RestSharp.RestRequest.AddParameter(RestSharp.Parameter)'匹配的最佳重载方法具有一些无效参数
和参数1:无法在此行上从'string'转换为'RestSharp.Parameter'
:
request.AddParameter(
"{'agent': { 'name': 'AgentHere', 'version': 1 }, 'username': 'Auth', 'password': 'Auth' }"
);
我无法使潜艇有效载荷
任何帮助都将不胜感激
谢谢 数据似乎是针对请求主体的。使用适当的
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);
为了避免手动构造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);