Post byte array to web api c#

POST Byte Array to Web API in C#

To post a byte array to a Web API in C#, you can use the HttpClient class available in the System.Net.Http namespace. Here’s an example:


using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        byte[] byteArray = GetByteArray();

        using (var client = new HttpClient())
        {
            // Set the request URL
            string url = "https://example.com/api/endpoint";
            
            // Create a ByteArrayContent object with the byte array
            var content = new ByteArrayContent(byteArray);
            
            // Set the content type header
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
            
            // Send the POST request to the Web API
            var response = await client.PostAsync(url, content);
            
            // Check if the response was successful
            if (response.IsSuccessStatusCode)
            {
                // Read the response content
                string responseBody = await response.Content.ReadAsStringAsync();
                
                Console.WriteLine("Response: " + responseBody);
            }
            else
            {
                Console.WriteLine("Request failed with status code: " + response.StatusCode);
            }
        }
    }

    static byte[] GetByteArray()
    {
        // Example method to get a byte array
        string text = "Hello, world!";
        
        return System.Text.Encoding.UTF8.GetBytes(text);
    }
}
    

In this example, we have a Main method that sends a POST request to a Web API endpoint. It first creates a byte array using the GetByteArray method (you can replace this with your own byte array generation logic). Then, it creates an instance of the HttpClient class and sets the request URL. The byte array is converted into a ByteArrayContent object, and the content type header is set to “application/octet-stream” (change this if your API requires a different content type). Finally, the POST request is sent using the PostAsync method, and the response content is read and displayed.

Leave a comment