RestSharp JSON 参数发布 [英] RestSharp JSON Parameter Posting

查看:31
本文介绍了RestSharp JSON 参数发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我的 MVC 3 API 进行非常基本的 REST 调用,但我传入的参数未绑定到操作方法.

I am trying to make a very basic REST call to my MVC 3 API and the parameters I pass in are not binding to the action method.

客户

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
}

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

您不必自己序列化正文.就做

You don't have to serialize the body yourself. Just do

request.RequestFormat = DataFormat.Json;
request.AddJsonBody(new { A = "foo", B = "bar" }); // Anonymous type object is converted to Json body

如果您只想要 POST 参数(它仍然会映射到您的模型并且效率更高,因为没有序列化到 JSON),请执行以下操作:

If you just want POST params instead (which would still map to your model and is a lot more efficient since there's no serialization to JSON) do this:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");

这篇关于RestSharp JSON 参数发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆