Home > Net >  How to convert to a data model to http content in Post Async
How to convert to a data model to http content in Post Async

Time:12-13

Now if I wanna send a http content I use dictionary and then convert it into http content and then I send in

but I wanna convert a object to a http content directly

what now I do :

            var contentDictionary = new Dictionary<string, string>()
            {
                { "customerId",customerId.ToString()}
            };
            var httpContentData = new FormUrlEncodedContent(contentDictionary );
            var request= await _httpClient.PostAsync(url,httpContentData );

what I want to do but I don't know how to do it :

var obj =new custome(){CustomerId=customerId};
...
//do something
...
var request= await _httpClient.PostAsync(url,httpContent );

I used some kind of syntax but it did not work for me and now I'm looking for some kind of NuGet or libary or syntax that can help me in this case

CodePudding user response:

I guess you are looking for the below one.

 tickets tickets = new tickets
    {
        ticket = ticket
    };

    string comments= System.Text.Json.JsonSerializer.Serialize(tickets);

var httpResponseMessage = await httpClient.PostAsync(
        uriLink, new StringContent(comments, System.Text.Encoding.UTF8, _mediaType));

CodePudding user response:

To convert a data model to HTTP content in a PostAsync method, you can use the JsonSerializer class from the System.Text.Json namespace. This class provides methods for serializing objects to JSON data and deserializing JSON data to objects

  • Related