Interface IHttpResponseFeature

Namespace: Microsoft.AspNetCore.Http

Summary

Represents a feature that provides information about the HTTP response.

This interface is part of the ASP.NET Core middleware pipeline and is used to interact with and control the outgoing HTTP response.

Members

Properties

Methods

Remarks

The IHttpResponseFeature interface is a fundamental part of how ASP.NET Core handles HTTP responses. Middleware components can inspect and modify this feature to alter the response before it's sent to the client.

When a server implements ASP.NET Core, it provides an implementation of this interface. Features are typically accessed via the IFeatureCollection on the HttpContext.

Usage Example


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

public class CustomResponseMiddleware
{
    private readonly RequestDelegate _next;

    public CustomResponseMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var responseFeature = context.Features.Get<IHttpResponseFeature>();

        if (responseFeature != null)
        {
            responseFeature.OnStarting(async () =>
            {
                // Set custom header before response starts
                responseFeature.Headers["X-Custom-Header"] = "MyValue";
                Console.WriteLine("Response is starting...");
            });

            responseFeature.OnCompleted(async () =>
            {
                // Log after response is completed
                Console.WriteLine("Response completed.");
            });

            // You can also directly manipulate properties:
            responseFeature.StatusCode = 200;
            responseFeature.ReasonPhrase = "OK";

            // Write to the response body
            byte[] responseBytes = Encoding.UTF8.GetBytes("Hello from Custom Middleware!");
            await responseFeature.Body.WriteAsync(responseBytes, 0, responseBytes.Length);
        }

        // Call the next middleware in the pipeline
        await _next(context);
    }
}