我试图对我的MVC3API进行一个非常基本的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
}
我是不是漏掉了什么?
发布于 2011-06-11 07:31:50
您不必自己序列化正文。只管去做
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body
如果你只是想要POST参数(它仍然会映射到你的模型,而且效率更高,因为没有序列化到JSON),那么这样做:
request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
发布于 2017-02-01 07:34:46
在当前版本的RestSharp (105.2.3.0)中,您可以通过以下方式将JSON对象添加到请求体:
request.AddJsonBody(new { A = "foo", B = "bar" });
此方法将内容类型设置为application/json,并将对象序列化为JSON字符串。
发布于 2016-01-21 23:58:40
这就是对我有效的方法,对于我的情况,这是一个登录请求的post:
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":"sam@company.com" ,
"password":"welcome"
}
https://stackoverflow.com/questions/6312970
复制相似问题