我试图对我的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参数(它仍将映射到您的模型,并且由于没有序列化到JSON而效率更高),请执行以下操作:
request.AddParameter("A", "foo"); request.AddParameter("B", "bar");