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 Provides access to response properties like status code, headers, and body.
- Methods Provides methods to manipulate the response, such as writing data or sending headers.
Properties
-
StatusCode
int
StatusCode {get; set;
} Gets or sets the HTTP status code associated with the response. -
Headers
IHeaderDictionary
Headers {get;
} Gets the collection of HTTP response headers. -
Body
Stream
Body {get; set;
} Gets or sets the response body stream. -
ReasonPhrase
string
ReasonPhrase {get; set;
} Gets or sets the HTTP reason phrase for the status code. -
HasStarted
bool
HasStarted {get;
} Gets a value indicating whether the response has started sending to the client.
Methods
-
OnStarting
Task
OnStarting(Func<Task>
callback,object
state) Registers a callback delegate that will be invoked when the response starts sending. This is often used to set final headers or perform other pre-send actions. -
OnCompleted
Task
OnCompleted(Func<Task>
callback,object
state) Registers a callback delegate that will be invoked after the response has completed sending. This is useful for cleanup operations or logging.
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);
}
}