make a http put request in csharp

To make a PUT request in C#, you can use the HttpWebRequest class which provides methods for sending HTTP requests to a web server. Here is an example code snippet that demonstrates how to make a PUT request:

main.cs
string url = "https://example.com/api/resource";
string payload = "{\"name\": \"John Doe\", \"age\": 30}";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/json";
request.Accept = "application/json";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(payload);
    writer.Flush();
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    string result = reader.ReadToEnd();
    Console.WriteLine(result); 
}
625 chars
22 lines

In this example, we are making a PUT request to the https://example.com/api/resource URL with a JSON payload containing the name and age of a person. We set the Method property of the HttpWebRequest object to "PUT" to specify that we want to make a PUT request. We also set the ContentType property to "application/json" to indicate that we are sending a JSON payload, and the Accept property to "application/json" to specify that we want to receive the response in JSON format.

We then write the payload to the request stream using a StreamWriter. After sending the request, we read the response using a StreamReader and output the result to the console.

Note that this is a basic example and you may need to modify it based on your specific requirements, such as adding headers, handling errors, or deserializing the response into an object.

gistlibby LogSnag