我正在尝试对我的MVC 3 API进行非常基本的REST调用,并且我传入的参数不绑定到action方法。
客户
var request = new RestRequest(Method.POST);
request.Resource = "Api/Score";
request.RequestFormat = DataFormat.Json;
request.AddBody(request.JsonSerializer.Serialize(new { A = "foo", B = "bar" }));
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
服务器
public class ScoreInputModel
{
public string A { get; set; }
public string B { get; set; }
}
// Api/Score
public JsonResult Score(ScoreInputModel input)
{
// input.A and input.B are empty when called with RestSharp
}
我在这里错过了什么吗?
您不必自己序列化身体。做就是了
request.RequestFormat = DataFormat.Json;
request.AddBody(new { A = "foo", B = "bar" }); // uses JsonSerializer
如果您只想要POST params(它仍然会映射到您的模型并且由于没有序列化到JSON而效率更高),请执行以下操作:
request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
在当前版本的RestSharp(105.2.3.0)中,您可以使用以下命令将JSON对象添加到请求正文:
request.AddJsonBody(new { A = "foo", B = "bar" });
此方法将内容类型设置为application / json,并将对象序列化为JSON字符串。
这对我有用,对我来说这是一个登录请求的帖子:
var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content; // raw content as string
身体 :
{
"userId":"[email protected]" ,
"password":"welcome"
}
希望这会对某人有所帮助。它对我有用 -
RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
Host = "host_environment",
Username = "UserID",
Password = "Password"
};
request.AddJsonBody(body);
var response = client.Execute(request).Content;
如果您有List
对象,可以将它们序列化为JSON,如下所示:
List<MyObjectClass> listOfObjects = new List<MyObjectClass>();
然后使用addParameter
:
requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));
您需要将请求格式设置为qazxsw poi:
JSON