RestSharp JSON 参数发布
我正在尝试对 MVC 3 API 进行非常基本的 REST 调用,并且我传入的参数未绑定到操作方法。
客户端
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
}
我在这里遗漏了什么吗?
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.
Client
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);
Server
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您不必自己序列化主体。 :
如果您只想使用 POST 参数(它仍然会映射到您的模型,并且效率更高,因为没有序列化为 JSON),请执行以下操作
You don't have to serialize the body yourself. Just do
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:
在当前版本的 RestSharp (105.2.3.0) 中,您可以使用以下方法将 JSON 对象添加到请求正文:
此方法将内容类型设置为 application/json 并将对象序列化为 JSON 字符串。
In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:
This method sets content type to application/json and serializes the object to a JSON string.
这对我有用,对于我来说,这是登录请求的帖子:
正文:
This is what worked for me, for my case it was a post for login request :
body :
希望这会对某人有所帮助。它对我有用 -
Hope this will help someone. It worked for me -
如果你有一个
List
对象,你可以将它们序列化为JSON,如下所示:然后使用
addParameter
:并且你需要将请求格式设置为
JSON :
If you have a
List
of objects, you can serialize them to JSON as follow:And then use
addParameter
:And you wil need to set the request format to
JSON
:您可能需要从请求正文中反序列化匿名 JSON 类型。
You might need to Deserialize your anonymous JSON type from the request body.
这是完整的控制台工作应用程序代码。请安装 RestSharp 软件包。
Here is complete console working application code. Please install RestSharp package.