It seems like I can use HttpContext.Features
and HttpContext.Items
to store some data to share with different classes with access to HttpContext
.
Are there some situations where I should prefer one over another? Or it's purely up to me? Is it wrong to use one of them in certain circumstances?
Hi @ayepirate.
The Features property of HttpContext provides an interface for getting and setting the available HTTP features for the current request. Since the feature collection is mutable even within the context of a request, middleware can be used to modify the collection and add support for additional features.
So only features can be registered with the Features
collection. Source: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/request-features?view=aspnetcore-2.0
To pass arbitrary data between different aspects of your code withing the scope of the request you should use the Items
collection: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/request-features?view=aspnetcore-2.0
@mkArtakMSFT but I can create my own features and set them. And share data this way, so what's the difference.
While servers are responsible for creating the feature collection, middleware can both add to this collection and consume features from the collection. For example, the StaticFileMiddleware accesses the IHttpSendFileFeature feature. If the feature exists, it's used to send the requested static file from its physical path. Otherwise, a slower alternative method is used to send the file. When available, the IHttpSendFileFeature allows the operating system to open the file and perform a direct kernel mode copy to the network card.
Features are more of an explicit contract between implementation and consumer. They can have more meaning and also expose behavior not just state. Items are actually implemented via a feature. Items are a generic dictionary made to round trip state between things that have access to the http context.
Most helpful comment
Features are more of an explicit contract between implementation and consumer. They can have more meaning and also expose behavior not just state. Items are actually implemented via a feature. Items are a generic dictionary made to round trip state between things that have access to the http context.