Publicación de parámetros RestSharp JSON


Estoy tratando de hacer una llamada REST muy básica a mi API MVC 3 y los parámetros que paso no son vinculantes para el método action.

Cliente

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);

Servidor

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
}

¿Me estoy perdiendo algo aquí?

Author: Wesley Tansey, 2011-06-11

4 answers

Usted no tiene que serializar el cuerpo usted mismo. Solo hazlo

request.RequestFormat = DataFormat.Json;
request.AddBody(new { A = "foo", B = "bar" }); // uses JsonSerializer

Si solo desea POST params en su lugar (que todavía se mapearía a su modelo y es mucho más eficiente ya que no hay serialización a JSON) haga esto:

request.AddParameter("A", "foo");
request.AddParameter("B", "bar");
 175
Author: John Sheehan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-17 16:27:39

Esto es lo que funcionó para mí, para mi caso fue un post para la solicitud de inicio de sesión:

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  

Cuerpo:

{
  "userId":"[email protected]" ,
  "password":"welcome" 
}
 31
Author: Soumyaansh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 15:58:39

En la versión actual de RestSharp (105.2.3.0) puede agregar un objeto JSON al cuerpo de la solicitud con:

request.AddJsonBody(new { A = "foo", B = "bar" });

Este método establece content type en application/json y serializa el objeto en una cadena JSON.

 29
Author: Chris Morgan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-31 23:34:45

Si tienes un List de objetos, puedes serializarlos a JSON de la siguiente manera:

List<MyObjectClass> listOfObjects = new List<MyObjectClass>();

Y luego use addParameter:

requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));

Y tendrá que establecer el formato de solicitud en JSON:

requestREST.RequestFormat = DataFormat.Json;
 0
Author: tomloprod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 16:32:35