一尘不染

RestSharp发布一个JSON对象

json

我正在尝试使用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";
    }
}

谁能告诉我我在做什么错?还有其他方法可以发布安全性问题对象吗?

非常感谢。


阅读 357

收藏
2020-07-27

共1个答案

一尘不染

您需要在标题中指定content-type:

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

AddParameter根据方法添加到POST或URL查询字符串

我认为您需要像这样将其添加到主体中:

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