Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Question: HttpContext.Features vs HttpContext.Items #7833

Closed
bugproof opened this issue May 29, 2018 · 3 comments
Closed

Question: HttpContext.Features vs HttpContext.Items #7833

bugproof opened this issue May 29, 2018 · 3 comments
Labels

Comments

@bugproof
Copy link

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?

@mkArtakMSFT
Copy link
Member

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

@bugproof
Copy link
Author

bugproof commented May 29, 2018

@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.

@davidfowl
Copy link
Member

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants