Build HttpClient which mimic our PostMan settings

john john 946 Reputation points
2022-10-17T21:43:20.91+00:00

I am testing an API which i developed using ASP.NET MVC-5. now I set the follwoing setting inside PostMan tool:-

1) Header:-
enter image description here

2) Body:-
251205-image.png

now we want to use .NET HttpClient to call the api, so how i can set the "Content-Type= application/json" for the header + "x-www-form-urlencoded" for the body?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,648 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,417 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-10-17T22:02:58.273+00:00

    you postman setting make no sense.

    your post header say the body will be json, but in the body, instead of json you are using form-urlencoded.

    postman body editor is just a simple formatter. form url encoded is same as query string encoding:

    name1=value1&name2=value2

    the names and the values should be url encoded. if using a form post, then content-type header should be x-www-form-urlencoded

    note: it looks like an old postman. to send json. you should set the content-type=application/json and use raw body. enter valid json.


  2. Bruce (SqlWork.com) 61,731 Reputation points
    2022-10-19T23:08:26.583+00:00

    seems odd you would use form encoded for an api, but its something like:

     var client = new HttpClient();  
     var data = new[]  
     {  
            new KeyValuePair<string, string>("username", "John Doe"),  
            new KeyValuePair<string, string>("email", "johndoe@example.com"),  
     };  
    var response = await  client.PostAsync(endPoint, new FormUrlEncodedContent(data));  
      
    
    0 comments No comments