RestSharp JSON Parameter Posting
-
26-10-2019 - |
سؤال
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?
المحلول
You don't have to serialize the body yourself. Just do
request.RequestFormat = DataFormat.Json;
request.AddBody(new { A = "foo", B = "bar" }); // uses JsonSerializer
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");
نصائح أخرى
In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:
request.AddJsonBody(new { A = "foo", B = "bar" });
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 :
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
body :
{
"userId":"sam@company.com" ,
"password":"welcome"
}
Hope this will help someone. It worked for me -
RestClient client = new RestClient("http://www.example.com/");
RestRequest request = new RestRequest("login", Method.POST);
request.AddHeader("Accept", "application/json");
var body = new
{
Host = "host_environment",
Username = "UserID",
Password = "Password"
};
request.AddJsonBody(body);
var response = client.Execute(request).Content;
If you have a List
of objects, you can serialize them to JSON as follow:
List<MyObjectClass> listOfObjects = new List<MyObjectClass>();
And then use addParameter
:
requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));
And you wil need to set the request format to JSON
:
requestREST.RequestFormat = DataFormat.Json;