0

Now if I want to send http content I use dictionary and then convert it into http content and then I send in, but I want to convert a object to a http content directly.

What I do now:

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.

5
  • What do you want to do? http content covers all possible content types. What does the remote URL expect? A FORM post? JSON? A CSV file? Some other format? Commented Dec 13, 2022 at 8:02
  • The code you use now works fine if the remote API expects a FORM post. If it wants JSON you can use .PostAsJsonAsync(url,customer), or you can serialize the customer object to a JSON string and wrap it in a JsonContent. Commented Dec 13, 2022 at 8:05
  • Is the actual question how to convert any object to FormUrlEncodedContent? There's a similar question: Build URL encoded query from model object for HttpClient. The answers show how to use reflection to read all properties or use a JSON serializer to help handle complex objects Commented Dec 13, 2022 at 8:16
  • I know the code is fine but now I use a new method that except dictionary I mean an easier way to make http content like convert object to http content or something else Commented Dec 13, 2022 at 8:34
  • I already posted a link with multiple answers Commented Dec 13, 2022 at 8:38

1 Answer 1

-2

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));
Sign up to request clarification or add additional context in comments.

4 Comments

The question is how to generate whatever is in comments, not how to post a raw string
@PanagiotisKanavos - I have updated the answer>please look into it.
If the OP wanted JSON, PostAsJsonAsync would do. There's a specialized JsonContent type as well. We don't know what the OP wants to generate
thank you for your answer but it didn't work , I wanted to convert an object to a http content 🙏

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.