使用子有效载荷将JSON数据发送到REST API

时间:2018-08-06 00:39:53

标签: c# json restsharp

我正在尝试使用C#应用程序将JSON数据发送到REST API

JSON数据应如下所示:

{
    'agent': {
        'name': 'AgentHere',
        'version': 1
    },
    'username': 'Auth',
    'password': 'Auth'
}

因此,如您所见... agent具有nameversion

的子有效载荷

我正在这样使用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

但是我在此行收到错误The best overloaded method match for 'RestSharp.RestRequest.AddParameter(RestSharp.Parameter)' has some invalid argumentsArgument 1: cannot convert from 'string' to 'RestSharp.Parameter'

request.AddParameter(
            "{'agent': { 'name': 'AgentHere', 'version': 1 }, 'username': 'Auth', 'password': 'Auth' }"
        );

我无法使子有效载荷

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:2)

数据似乎是为请求正文提供的。使用适当的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);