HttpResponse

Represents an HTTP response sent from the server to the client.

Namespace: Microsoft.AspNetCore.Http

Class: HttpResponse

Inheritance: object

Overview

The HttpResponse interface provides a way to construct and send an HTTP response. It exposes properties and methods to set status codes, headers, cookies, and write the response body.

Properties

StatusCode

Gets or sets the status code of the response.

int StatusCode { get; set; }

Use this property to set the HTTP status code (e.g., 200 for OK, 404 for Not Found).

Headers

Gets a collection of HTTP response headers.

IHeaderDictionary Headers { get; }

Use the Headers property to add or modify response headers like Content-Type or custom headers.

Body

Gets or sets the HTTP response body.

Stream Body { get; set; }

The Body property provides access to a Stream where you can write the response content.

ContentType

Gets or sets the value of the Content-Type header.

string ContentType { get; set; }

A convenient way to set the Content-Type header for the response.

Methods

Redirect

Applies a permanent redirect to the specified URL.

void Redirect(string url, bool permanent = false)

Use this method to redirect the client to a different URL. Set permanent to true for a permanent redirect (301) or false for a temporary redirect (302).

// Example: Redirect to the homepage
context.Response.Redirect("/");

// Example: Permanent redirect to another page
context.Response.Redirect("/about", true);
            

WriteAsync

Writes content asynchronously to the response body.

Task WriteAsync(string text, CancellationToken cancellationToken = default)

Task WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default)

Write string data or byte arrays to the response body asynchronously.

// Writing a string
await context.Response.WriteAsync("Hello, World!");

// Writing bytes
byte[] data = { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // "Hello" in bytes
await context.Response.WriteAsync(data);
            

HasStarted

Gets a value indicating whether the response has started.

bool HasStarted { get; }

This property is useful for checking if headers or body have already been sent, preventing further modifications.