ASP.NET Core Features
Introduction
Request Features, or feature interfaces, offer a centralised way to access functionality that is commonly added by middleware in the pipeline. Features allow us to access information, or, in some case, control the behaviour of the middleware they belong to.
Some examples include:
-
IException
Handler Feature and IException Handler Path Feature: allows us to get the exception that ocurred and also the path of the request -
IHttp
Connection Feature: where we can get all information from the current client connection - IIISEnvironment
Feature: to get information from the hosting IIS (if in use)
- IServer
Addresses Feature: for the exposed paths and URLs
And many more. A feature is only present if its service/middleware was registered, for example, the Kestrel or the IIS features will only be available if we are using one host or the other.
The way to access a feature is through the HttpContext.Features collection:
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = exceptionFeature.Error;
Some of the information that is made available through a feature is also exposed as discrete properties:
- IHttp
Connection Feature: exposed by HttpContext.Connection
Another example, to close/shutdown the existing client connection:
var connectionFeature = HttpContext.Features.Get<IConnectionLifetime Notification Feature>();
connectionFeature.RequestClose();
Or, to know the URLs that the server is listening to:
var addressesFeature = HttpContext.Features.Get<IServerAddressesFeature>();
var boundAddresses = addressesFeature.Addresses;
Now, the feature list.
Features List
The features included in ASP.NET Core are as follows:
Please have a look at each of the interfaces (long list, I know!) to find out more about each. Again, don't forget that some may not be present on your system, depending on your registered services, hosting, etc.
Adding Features
You can add a feature to the HttpContext.Features collection by calling its Set method:
HttpContext.Features.Set<IMyFeature>(new MyFeature());
There is no base interface or anything that you need to adhere to, but you must pass a concrete instance. Oh, and this needs to be added o each request, unlike request services.
Conclusion
Request Features offers a convenient way to control and access information about the executing host and middleware, but we need to know the right interfaces, which is not always easy. I hope this list comes in handy!