HttpContent Class

Definition

A base class representing an HTTP entity body and content headers.

public ref class HttpContent abstract : IDisposable
public abstract class HttpContent : IDisposable
type HttpContent = class
    interface IDisposable
Public MustInherit Class HttpContent
Implements IDisposable
Inheritance
HttpContent
Derived
Implements

Examples

The following example shows a custom implementation of HttpContent. Some methods, despite being defined as virtual and not abstract, should still be overridden in the implementation for optimal behavior.

public class MyContent : HttpContent
{
    private readonly string _data;
    public MyContent(string data)
    {
        _data = data;
    }

    // Minimal implementation needed for an HTTP request content,
    // i.e. a content that will be sent via HttpClient, contains the 2 following methods.
    protected override bool TryComputeLength(out long length)
    {
        // This content doesn't support pre-computed length and
        // the request will NOT contain Content-Length header.
        length = 0;
        return false;
    }

    // SerializeToStream* methods are internally used by CopyTo* methods
    // which in turn are used to copy the content to the NetworkStream.
    protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context)
        => stream.WriteAsync(Encoding.UTF8.GetBytes(_data)).AsTask();

    // Override SerializeToStreamAsync overload with CancellationToken
    // if the content serialization supports cancellation, otherwise the token will be dropped.
    protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken)
        => stream.WriteAsync(Encoding.UTF8.GetBytes(_data), cancellationToken).AsTask();

    // In rare cases when synchronous support is needed, e.g. synchronous CopyTo used by HttpClient.Send,
    // implement synchronous version of SerializeToStream.
    protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken)
        => stream.Write(Encoding.UTF8.GetBytes(_data));

    // CreateContentReadStream* methods, if implemented, will be used by ReadAsStream* methods
    // to get the underlying stream and avoid buffering.
    // These methods will not be used by HttpClient on a custom content.
    // They are for content receiving and HttpClient uses its own internal implementation for an HTTP response content.
    protected override Task<Stream> CreateContentReadStreamAsync()
        => Task.FromResult<Stream>(new MemoryStream(Encoding.UTF8.GetBytes(_data)));

    // Override CreateContentReadStreamAsync overload with CancellationToken
    // if the content serialization supports cancellation, otherwise the token will be dropped.
    protected override Task<Stream> CreateContentReadStreamAsync(CancellationToken cancellationToken)
        => Task.FromResult<Stream>(new MemoryStream(Encoding.UTF8.GetBytes(_data))).WaitAsync(cancellationToken);

    // In rare cases when synchronous support is needed, e.g. synchronous ReadAsStream,
    // implement synchronous version of CreateContentRead.
    protected override Stream CreateContentReadStream(CancellationToken cancellationToken)
        => new MemoryStream(Encoding.UTF8.GetBytes(_data));
}

Remarks

There are various HTTP contents that can be used. These include the following.

  1. ByteArrayContent - A content represented by a byte array, also serves as a base class for StringContent and FormUrlEncodedContent.

  2. StringContent - A string-based content, by default serialized as text/plain Content-Type with UTF-8 encoding.

  3. FormUrlEncodedContent - A content with name/value tuples serialized as application/x-www-form-urlencoded Content-Type.

  4. MultipartContent - A content that can serialize multiple different HttpContent objects as multipart/* Content-Type.

  5. JsonContent - A content that serializes objects as application/json Content-Type with UTF-8 encoding by default.

HTTP content class can be derived by a user to provide custom content serialization logic.

Constructors

HttpContent()

Initializes a new instance of the HttpContent class.

Properties

Headers

Gets the HTTP content headers as defined in RFC 2616.

Methods

CopyTo(Stream, TransportContext, CancellationToken)

Serializes the HTTP content into a stream of bytes and copies it to stream.

CopyToAsync(Stream)

Serialize the HTTP content into a stream of bytes and copies it to the stream object provided as the stream parameter.

CopyToAsync(Stream, CancellationToken)

Serialize the HTTP content into a stream of bytes and copies it to the stream object provided as the stream parameter.

CopyToAsync(Stream, TransportContext)

Serialize the HTTP content into a stream of bytes and copies it to the stream object provided as the stream parameter.

CopyToAsync(Stream, TransportContext, CancellationToken)

Serialize the HTTP content into a stream of bytes and copies it to the stream object provided as the stream parameter.

CreateContentReadStream(CancellationToken)

Serializes the HTTP content to a memory stream.

CreateContentReadStreamAsync()

Serialize the HTTP content to a memory stream as an asynchronous operation.

CreateContentReadStreamAsync(CancellationToken)

Serializes the HTTP content to a memory stream as an asynchronous operation.

Dispose()

Releases the unmanaged resources and disposes of the managed resources used by the HttpContent.

Dispose(Boolean)

Releases the unmanaged resources used by the HttpContent and optionally disposes of the managed resources.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
LoadIntoBufferAsync()

Serialize the HTTP content to a memory buffer as an asynchronous operation.

LoadIntoBufferAsync(Int64)

Serialize the HTTP content to a memory buffer as an asynchronous operation.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ReadAsByteArrayAsync()

Serialize the HTTP content to a byte array as an asynchronous operation.

ReadAsByteArrayAsync(CancellationToken)

Serialize the HTTP content to a byte array as an asynchronous operation.

ReadAsStream()

Serializes the HTTP content and returns a stream that represents the content.

ReadAsStream(CancellationToken)

Serializes the HTTP content and returns a stream that represents the content.

ReadAsStreamAsync()

Serialize the HTTP content and return a stream that represents the content as an asynchronous operation.

ReadAsStreamAsync(CancellationToken)

Serialize the HTTP content and return a stream that represents the content as an asynchronous operation.

ReadAsStringAsync()

Serialize the HTTP content to a string as an asynchronous operation.

ReadAsStringAsync(CancellationToken)

Serialize the HTTP content to a string as an asynchronous operation.

SerializeToStream(Stream, TransportContext, CancellationToken)

When overridden in a derived class, serializes the HTTP content to a stream. Otherwise, throws a NotSupportedException.

SerializeToStreamAsync(Stream, TransportContext)

Serialize the HTTP content to a stream as an asynchronous operation.

SerializeToStreamAsync(Stream, TransportContext, CancellationToken)

Serialize the HTTP content to a stream as an asynchronous operation.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
TryComputeLength(Int64)

Determines whether the HTTP content has a valid length in bytes.

Extension Methods

ReadFromJsonAsync(HttpContent, Type, JsonSerializerOptions, CancellationToken)

Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation.

ReadFromJsonAsync(HttpContent, Type, JsonSerializerContext, CancellationToken)

Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation.

ReadFromJsonAsync<T>(HttpContent, JsonSerializerOptions, CancellationToken)

Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation.

ReadFromJsonAsync<T>(HttpContent, JsonTypeInfo<T>, CancellationToken)

Reads the HTTP content and returns the value that results from deserializing the content as JSON in an asynchronous operation.

Applies to