问题描述
这两个属性之间有什么区别?
我可以使用HttpContext.Items
代替HttpContext.Features
在middlewares
之间共享数据.我看到的唯一区别是,我告诉Items
一个密钥,它给了我对象,因此我必须强制转换它.可以自动在Features
中完成投射.
I can use HttpContext.Items
instead of HttpContext.Features
to share data between middlewares
. The only difference i see is that i tell Items
for a key and it gives me object and i have to cast it. This casting can be done in Features
automatically.
他们身后还有别的东西吗?
Is there something else behind them?
推荐答案
最大的区别是HttpContext.Items
设计为存储Key-Value-Pair
,而HttpContext.Features
设计为存储Type-Instance-Pair
.
The biggest difference is that the HttpContext.Items
is designed to store Key-Value-Pair
, while the HttpContext.Features
is designed to store Type-Instance-Pair
.
更清楚地说,HttpContext.Items
旨在共享当前请求范围内的项目,而作为IFeatureCollection
实例的HttpContext.Features
绝不能那样使用.
To be more clear, HttpContext.Items
is designed to share items within the scope of current request, while the HttpContext.Features
, which is an instance of IFeatureCollection
, is by no means to be used like that .
IFeatureCollection
接口表示HTTP功能的集合,例如:
The IFeatureCollection
interface represents a collection of HTTP features, such as:
-
IAuthenticationFeature
,用于存储原始PathBase和原始Path. -
ISessionFeature
存储当前会话. -
IHttpConnectionFeature
存储基础连接. - 以此类推.
IAuthenticationFeature
which stores original PathBase and original Path.ISessionFeature
which stores current Session.IHttpConnectionFeature
which stores the underlying connection.- and so on.
为帮助存储和检索Type-Instance-Pair
,该界面具有三种重要方法:
To help store and retrieve a Type-Instance-Pair
, the interface has three important methods:
public interface IFeatureCollection : IEnumerable<KeyValuePair<Type, object>>{
// ...
object this[Type key] { get; set; }
TFeature Get<TFeature>();
void Set<TFeature>(TFeature instance);
}
和实现(FeatureCollection
)会将值简单地转换为所需的类型:
and the implementation (FeatureCollection
) will simply cast the value into required type:
public class FeatureCollection : IFeatureCollection
{
// ... get the required type of feature
public TFeature Get<TFeature>()
{
return (TFeature)this[typeof(TFeature)]; // note: cast here!
}
public void Set<TFeature>(TFeature instance)
{
this[typeof(TFeature)] = instance; // note!
}
}
这是设计使然.因为不需要存储两个IHttpConnectionFeature
实例或两个ISession
实例.
This is by design. Because there's no need to store two IHttpConnectionFeature
instances or two ISession
instances.
虽然可以用FeatureCollection
存储一些Type-Value
对,但最好不要.如您所见,如果集合中已经存在某种类型的Set<TFeature>(TFeature instance)
,它将简单地替换旧的.如果您有两个相同的类型,这也意味着会出现错误.
While you can store some Type-Value
pairs with FeatureCollection
, you'd better not . As you see, the Set<TFeature>(TFeature instance)
will simply replace the old one if the some type already exists in the collection; it also means there will be a bug if you have two of the same type.
这篇关于Asp.Net Core中的HttpContext.Features与HttpContext.Items的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!