Domanda

Sto cercando di fare una chiamata molto di base REST alla mia MVC 3 API ed i parametri che passano non sono vincolanti per il metodo di azione.

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
}

mi manca qualcosa qui?

È stato utile?

Soluzione

Non c'è bisogno di serializzare il corpo da soli. Basta fare

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

Se si desidera solo POST params invece (che sarebbe comunque mappa al tuo modello ed è molto più efficiente, in quanto non c'è serializzazione JSON) fare questo:

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

Altri suggerimenti

Nella versione attuale di RestSharp (105.2.3.0) è possibile aggiungere un oggetto JSON al corpo richiesta con:

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

Questo tipo di contenuto metodo imposta a application / json e serializza l'oggetto in una stringa JSON.

Questo è ciò che ha funzionato per me, per il mio caso si trattava di un messaggio per la richiesta di login:

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  

del corpo:

{
  "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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top