PostAsync Json C #

0

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 goal is to replace the XXXXXXX that are in the PostAsync so that in its place pass the information of the Ticket and that when sending to the respective link the content is the following:

{"input":[{"name": "TESTE", "content": "teste", "itilcategories_id":"1"}]}

Any ideas? Any questions please let me know !!

    
asked by anonymous 26.03.2018 / 17:10

1 answer

6

To reproduce the displayed 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 this object into a json and pass it as a StringContent() (adding the required headers) to your PostAsync() method.

Here's 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);
    
26.03.2018 / 17:29