我正在尝试对我的 MVC 3 API 进行非常基本的 REST 调用,并且我传入的参数未绑定(bind)到操作方法。
客户
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.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body
如果您只想要 POST 参数(它仍然会映射到您的模型并且效率更高,因为没有对 JSON 的序列化),请执行以下操作:
request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
关于c# - RestSharp JSON 参数发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6312970/