gpt4 book ai didi

c# - 从 View 组件中获取 session ID

转载 作者:行者123 更新时间:2023-11-30 23:06:12 27 4
gpt4 key购买 nike

这段代码可以很好地从 Controller 中获取 session ID:

HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = HttpContext.Session.Id;

...但是当我尝试将相同的代码放入 View 组件类时,VS 告诉我名称 HttpContext.Session.SetString(或只是 HttpContext.Session,或者只是 HttpContext) 在当前上下文中不存在。我在类(class)顶部有 using Microsoft.AspNetCore.Http;

编辑

这是我的 View 组件类:

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 实例上的方法,而不是静态方法。最简单的方法是让依赖注入(inject)框架给你一个IHttpContextAccessor。例如:

public class ShoppingCartViewComponent : ViewComponent
{
private readonly IHttpContextAccessor _contextAccessor;
private readonly MyStoreContext _context;

public ShoppingCartViewComponent(MyStoreContext context,
IHttpContextAccessor contextAccessor)
{
_context = context;
_contextAccessor = contextAccessor;

_contextAccessor.HttpContext.Session.SetString("_Name", "MyStore");
string SessionId = _contextAccessor.HttpContext.Session.Id;
}

//snip rest of code for brevity
}

关于c# - 从 View 组件中获取 session ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com