To make a HTTP request with a custom body as JSON in C#, you can use the HttpClient
class from the System.Net.Http
namespace. The following code snippet shows an example of how to make a POST request with a JSON body:
main.cs892 chars30 lines
In this example, we create an instance of the HttpClient
class and set the URI of the API endpoint we want to send the request to. The requestBody
variable contains the data we want to send in the request body, and we serialize it to JSON using JsonConvert.SerializeObject
from the Newtonsoft.Json package. We create a StringContent
instance from the serialized JSON and set its MediaType
property to application/json
. Finally, we use the PostAsync
method of the HttpClient
instance to send the POST request with the JSON body to the API endpoint. If the API returns a success status code, we read and print the response body. Otherwise, we print an error message with the status code of the response.
gistlibby LogSnag