【发布时间】:2018-06-30 07:33:48
【问题描述】:
这段代码可以很好地从控制器中获取会话 ID:
HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
...但是当我尝试将相同的代码放在视图组件类中时,VS 告诉我名称 HttpContext.Session.SetString(或只是 HttpContext.Session,或只是 HttpContext)在当前上下文中不存在.我有using Microsoft.AspNetCore.Http; 在班级顶部。
编辑
这是我的视图组件类:
public class ShoppingCartViewComponent : ViewComponent
{
private readonly MyStoreContext _context;
public ShoppingCartViewComponent(MyStoreContext context)
{
_context = context;
}
// Initialize session to enable SessionId
// THIS WON'T WORK:
HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;
public async Task<IViewComponentResult> InvokeAsync(int Id)
{
var cart = await GetCartAsync(Id);
return View(cart);
}
private async Task<ViewModelShoppingCart> GetCartAsync(int Id)
{
var VMCart = await _context.ShoppingCarts
.Where(c => c.Id == Id)
.Select(cart => new ViewModelShoppingCart
{
Id = cart.Id,
Title = cart.Title,
CreateDate = cart.CreateDate,
ShoppingCartItems = cart.ShoppingCartItems
.Select(items => new ViewModelShoppingCartItem
{
ProductId = items.ProductId,
ProductTitle = items.Product.Title,
ProductPrice = items.Product.Price,
Quantity = items.Quantity
}).ToList()
}).FirstOrDefaultAsync();
return VMCart;
}
}
【问题讨论】:
-
缺少哪位?
HttpContext自己工作吗?HttpContext.Session怎么样? -
@DavidG 以上都不是。
标签: c# session asp.net-core asp.net-core-viewcomponent