我想将一些代码升级到ASP.NET Core 2
。
我知道HttpContext.Current
已从ASP.NET Core 2
移除,必须使用IHttpContextAccessor
。
但我不知道如何替换这段代码:
HttpContext.Current.Items.Contains(DataContextKey)
我该怎么做?
完整的代码:
namespace Jahan.Infrastructure.DataAccess.DataContextStorage
{
public class HttpDataContextStorageContainer<T> : IDataContextStorageContainer<T> where T : class
{
private const string DataContextKey = "DataContext";
public T GetDataContext()
{
T objectContext = null;
if (HttpContext.Current.Items.Contains(DataContextKey))
{
objectContext = (T)HttpContext.Current.Items[DataContextKey];
}
return objectContext;
}
public void Clear()
{
if (HttpContext.Current.Items.Contains(DataContextKey))
{
HttpContext.Current.Items[DataContextKey] = null;
}
}
public void Store(T objectContext)
{
if (HttpContext.Current.Items.Contains(DataContextKey))
{
HttpContext.Current.Items[DataContextKey] = objectContext;
}
else
{
HttpContext.Current.Items.Add(DataContextKey, objectContext);
}
}
}
}
答案 0 :(得分:1)
注入HttpContext
并通过该访问权限访问当前public class HttpDataContextStorageContainer<T> : IDataContextStorageContainer<T> where T : class {
private const string DataContextKey = "DataContext";
private readonly IHttpContextAccessor accessor;
public HttpDataContextStorageContainer(IHttpContextAccessor accessor) {
this.accessor = accessor;
}
public T GetDataContext() {
var current = accessor.HttpContext;
T objectContext = null;
if (current.Items.ContainsKey(DataContextKey)) {
objectContext = (T)current.Items[DataContextKey];
}
return objectContext;
}
public void Clear() {
var current = accessor.HttpContext;
if (current.Items.ContainsKey(DataContextKey)) {
current.Items[DataContextKey] = null;
}
}
public void Store(T objectContext) {
var current = accessor.HttpContext;
if (current.Items.ContainsKey(DataContextKey)) {
current.Items[DataContextKey] = objectContext;
} else {
current.Items.Add(DataContextKey, objectContext);
}
}
}
。其余的应该足够简单,可以重构。
例如。
IHttpContextAccessor
确保services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
及其实现已在服务容器中注册。默认情况下不再添加它。
{
"0" : {
"Coordinates" : {
"Lat" : -29.00902,
"Long" : 31.98
}
},
"1" : {
"Coordinates" : {
"Lat" : -28.8,
"Long" : 30.00007
}
},
"num" : 1
}