HttpContentHeaders Class

This class provides access to the HTTP headers associated with an HTTP entity body. It is used by classes such as HttpContent to manage and retrieve HTTP headers that apply to the content payload.

Summary

HttpContentHeaders is a collection of standard HTTP headers, along with their corresponding values. It allows for easy manipulation of headers like Content-Type, Content-Length, Content-Encoding, and others.

Properties

  • ContentDisposition Gets or sets the value of the Content-Disposition header.
  • ContentEncoding Gets or sets the value of the Content-Encoding header.
  • ContentLanguage Gets or sets the value of the Content-Language header.
  • ContentLength Gets or sets the value of the Content-Length header.
  • ContentType Gets or sets the value of the Content-Type header.
  • Expires Gets or sets the value of the Expires header.
  • LastModified Gets or sets the value of the Last-Modified header.

Methods

  • Add(string name, string value) Adds an HTTP header to the collection.
  • Contains(string name) Determines whether the collection contains the specified header.
  • Get(string name) Gets the value of the specified HTTP header.
  • Remove(string name) Removes the specified HTTP header from the collection.

Example Usage

Here's how you might use HttpContentHeaders to set headers for an HTTP request:


using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

// Create a StringContent object with some data
var content = new StringContent("This is the request body.", Encoding.UTF8, "text/plain");

// Access the headers
HttpContentHeaders headers = content.Headers;

// Set common headers
headers.ContentType = new MediaTypeHeaderValue("application/json");
headers.ContentLength = 500; // Example: Set content length

// Add custom headers
headers.Add("X-Custom-Header", "MyValue");

// You can also get header values
string contentType = headers.ContentType.ToString();
string contentLength = headers.ContentLength.ToString();

Console.WriteLine($"Content-Type: {contentType}");
Console.WriteLine($"Content-Length: {contentLength}");
Console.WriteLine($"X-Custom-Header: {headers.GetValues("X-Custom-Header").FirstOrDefault()}");
                

Related Articles