Search code examples
asp.net-core.net-coredotnet-httpclient

How to add Content-Type: application/octet-stream to .Net Core header


I want to accomplish this, is there any trick

HttpClient c = new HttpClient();
c.DefaultRequestHeaders.Add("Content-type", "application/octet-stream"));

Solution

  • You should set content headers with HttpContent object, like below.

    var client = _clientFactory.CreateClient();
    
    using (var content = new ByteArrayContent(byteData))
    {
        content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
    
        var response = await client.PostAsync(uri, content);
    
        //code logic here
    
        //...
    }
    

    Besides, for more information about using IHttpClientFactory to create an HttpClient instance in ASP.NET Core, please check: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1