RestSharp发送JSON对象的POST请求

29

我正在尝试使用RestSharp发布以下JSON:

{"UserName":"UAT1206252627",
"SecurityQuestion":{
    "Id":"Q03",
    "Answer":"Business",
    "Hint":"The answer is Business"
},
}

我觉得我已经接近成功了,但似乎在SecurityQuestion方面遇到了困难(API报错说缺少一个参数,但没有说明是哪个参数)

目前我的代码如下:

var request = new RestRequest("api/register", Method.POST);
request.RequestFormat = DataFormat.Json;

request.AddParameter("UserName", "UAT1206252627");

SecurityQuestion securityQuestion = new SecurityQuestion("Q03");
request.AddParameter("SecurityQuestion", request.JsonSerializer.Serialize(securityQuestion));

IRestResponse response = client.Execute(request);

我的安全问题类看起来像这样:

public class SecurityQuestion
{
    public string id {get; set;}
    public string answer {get; set;}
    public string hint {get; set;}

    public SecurityQuestion(string id)
    {
         this.id = id;
         answer = "Business";
         hint = "The answer is Business";
    }
}

有人可以告诉我我做错了什么吗?还有其他发布“Security Question”对象的方法吗?

非常感谢。

5个回答

60

您需要在标头中指定内容类型:

request.AddHeader("Content-type", "application/json");

此外AddParameter根据Method将内容添加到POST或URL查询字符串中。

我认为你需要像这样将其添加到正文中:

request.AddJsonBody(
    new 
    {
      UserName = "UAT1206252627", 
      SecurityQuestion = securityQuestion
    }); // AddJsonBody serializes the object automatically

谢谢您的回答,Oluwafemi。但我仍然遇到同样的错误(缺少参数)- 我知道这似乎应该可以工作,但还有其他我可以尝试的吗? - JamesWillett
你能给出一个API的示例方法吗? - Oluwafemi
4
这对我有效:request.AddHeader("Content-Type", "application/json; charset=utf-8"); request.AddJsonBody(yourobject); 注:该代码用于向网络请求添加标题和JSON格式的请求体。 - Andrei Drynov
1
感谢您的解决方案。 - Thomas.Benz
1
真的不起作用。正确的方法是:r.AddParameter("application/json", JsonSerializerHelper.Serialize(keys), ParameterType.RequestBody); - lyolikaa
显示剩余2条评论

28

再次感谢您的帮助。为使其工作,我必须将所有内容提交为单个参数。以下是我最终使用的代码。

首先,我创建了两个类,称为“请求对象”和“安全问题”:

public class SecurityQuestion
{
    public string Id { get; set; }
    public string Answer { get; set; }
    public string Hint { get; set; }
}

public class RequestObject
{
    public string UserName { get; set; }
    public SecurityQuestion SecurityQuestion { get; set; }
}

然后我只需将其添加为单个参数,然后在发布之前将其序列化为JSON,就像这样:

var yourobject = new RequestObject
            {
                UserName = "UAT1206252627",
                SecurityQuestion = new SecurityQuestion
                {
                    Id = "Q03",
                    Answer = "Business",
                    Hint = "The answer is Business"
                },
            };
var json = request.JsonSerializer.Serialize(yourobject);

request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

它起作用了!


11

如果要发布原始的JSON正文字符串,则AddBody()或AddJsonBody()方法不起作用。请改用以下方法

request.AddParameter(
   "application/json",
   "{ \"username\": \"johndoe\", \"password\": \"secretpassword\" }", // <- your JSON string
   ParameterType.RequestBody);

1
是的,原始方法在许多情况下非常有用,例如当传递存储在数据库中的主体时。 - BigMan73

5

看起来最简单的方法是让RestSharp处理所有序列化。您只需要指定RequestFormat,就像这样。以下是我为正在处理的内容所想出的。

    public List<YourReturnType> Get(RestRequest request)
    {
        var request = new RestRequest
        {
            Resource = "YourResource",
            RequestFormat = DataFormat.Json,
            Method = Method.POST
        };
        request.AddBody(new YourRequestType());

        var response = Execute<List<YourReturnType>>(request);
        return response.Data;
    }

    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient(_baseUrl);

        var response = client.Execute<T>(request);
        return response.Data;
    }

2

RestSharp 支持通过 AddObject 方法从对象中添加参数。

request.AddObject(securityQuestion);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接