我正在尝试使用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";
}
}
谁能告诉我我做错了什么?有没有其他方式发布安全问题对象?
非常感谢。
答案 0 :(得分:41)
您需要在标题中指定内容类型:
String tag = (String) checkBox.getTag()
此外,if ( grep { $_ eq $in }@array ){
print "available\n";
}else{
print "not available\n";
}
根据方法
我认为您需要将它添加到正文中:
request.AddHeader("Content-type", "application/json");
答案 1 :(得分:19)
再次感谢您的帮助。为了实现这一点,我必须将所有内容作为单个参数提交。这是我最后使用的代码。
首先,我创建了几个名为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);
它有效!
答案 2 :(得分:3)
要发布原始json正文字符串,AddBody()或AddJsonBody()方法将无效。请改用以下内容
request.AddParameter(
"application/json",
"{ \"username\": \"johndoe\", \"password\": \"secretpassword\" }", // <- your JSON string
ParameterType.RequestBody);
答案 3 :(得分:1)
RestSharp
方法从对象支持 AddObject
request.AddObject(securityQuestion);
答案 4 :(得分:0)
看起来最简单的方法是让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;
}