Question:
I have the following class defined:
public class Ticket
{
public string name
public string content
public int itilcategories_id
}
And the following code sample:
static HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://stgsd.primaverabss.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
ticket.name = "TESTE";
ticket.content = "teste";
ticket.itilcategories_id = 1
HttpResponseMessage response = await client.PostAsync("apirest.php/Ticket/", XXXXXXXXX );
My objective is to replace the XXXXXXX that are in PostAsync so that the Ticket information is passed in its place and that when sending the respective link the content is as follows:
{"input":[{"name": "TESTE", "content": "teste", "itilcategories_id":"1"}]}
Any idea? Any questions let me know!!
Answer:
To reproduce the presented model, you need to create an object that has an attribute called input and that it receives an array or list of Tickets. Then you need to serialize that object into a json and pass it as a StringContent()
(adding the necessary headers) to your PostAsync()
method.
Here is an example:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://stgsd.primaverabss.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var ticket = new Ticket();
ticket.name = "TESTE";
ticket.content = "teste";
ticket.itilcategories_id = 1;
List<Ticket> tickets = new List<Ticket>();
tickets.Add(ticket);
var parametro = new
{
input = tickets.ToArray()
};
var jsonContent = JsonConvert.SerializeObject(parametro);
var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
contentString.Headers.ContentType = new
MediaTypeHeaderValue("application/json");
contentString.Headers.Add("Session-Token", session_token);
HttpResponseMessage response = await Client.PostAsync("apirest.php/Ticket/", contentString);