make a http request with a custom method in csharp

Here's an example of making an HTTP request with a custom method (in this case, a PATCH request) in C#:

main.cs
using System;
using System.Net;
using System.IO;

public static void MakeCustomHttpRequest(string url, string method, string data)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = method;

    if (data != null)
    {
        byte[] requestBody = System.Text.Encoding.UTF8.GetBytes(data);
        request.ContentType = "application/json";
        request.ContentLength = requestBody.Length;
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(requestBody, 0, requestBody.Length);
        }
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (Stream responseStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
        Console.WriteLine(reader.ReadToEnd());
    }
}
883 chars
28 lines

You can call this method with the URL you want to make the request to, the custom method (such as "PATCH"), and optionally, any data you want to send in the request body.

main.cs
string url = "https://example.com/items/123";
string method = "PATCH";
string data = "{ \"name\": \"new name\" }";

MakeCustomHttpRequest(url, method, data);
158 chars
6 lines

gistlibby LogSnag