RestSharp发布一个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"; } } 

谁能告诉我我做错了什么? 是否有其他方式发布安全问题对象?

非常感谢。

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

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

AddParameter也基于Method添加到POST或URL查询字符串

我认为你需要将它添加到身体中,如下所示:

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

再次感谢你的帮助。 为了实现这一点,我必须将所有内容作为单个参数提交。 这是我最后使用的代码。

首先,我做了几个名为Request Object和Security Question的类:

 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); 

它工作了!

通过AddObject方法从对象支持RestSharp

 request.AddObject(securityQuestion); 

要发布原始json正文字符串,AddBody()或AddJsonBody()方法将不起作用。 请改用以下内容

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

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

  public List Get(RestRequest request) { var request = new RestRequest { Resource = "YourResource", RequestFormat = DataFormat.Json, Method = Method.POST }; request.AddBody(new YourRequestType()); var response = Execute>(request); return response.Data; } public T Execute(RestRequest request) where T : new() { var client = new RestClient(_baseUrl); var response = client.Execute(request); return response.Data; }