使用HttpContext.Session.Get/Set报错:ISession无对应定义求助
解决ASP.NET Core Session中Get/Set方法未定义的错误
问题场景
构建简单电商系统时,需要将选中的商品列表存入订单报表,在使用HttpContext.Session.Get<List<Product>>和Set方法时,出现错误提示:ISession doesn't contain a definition for 'Get',Set方法也报相同错误。已引入Microsoft.AspNetCore.Http.Extensions、Microsoft.AspNetCore.Http、Microsoft.Extensions.Configuration命名空间,但问题仍未解决。
控制器代码
namespace EshopTest5.Controllers { public class OrderController : Controller { private readonly ApplicationDbContext _context; private readonly IHttpContextAccessor _httpcontext; public OrderController(ApplicationDbContext context, IHttpContextAccessor httpcontext) { _context = context; _httpcontext = httpcontext; } // GET: OrderController/Checkout public IActionResult Checkout() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Checkout(Order anOrder) { List<Product> products =_httpcontext.HttpContext.Session.Get<List<Product>>("products"); if (products != null) { foreach (var product in products) { OrderDetails orderDetails = new OrderDetails(); orderDetails.PorductId = product.ProductId; anOrder.OrderDetails.Add(orderDetails); } } anOrder.OrderNo = GetOrderNo(); _context.Orders.Add(anOrder); await _context.SaveChangesAsync(); HttpContext.Session.Set("products", new List<Product>()); return View(); } } }
Program.cs代码
using EshopTest5.Data; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddControllersWithViews(); builder.Services.AddHttpContextAccessor(); builder.Services.AddSession(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseSession(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run();
解决方案
1. 安装必要的NuGet包
ISession的泛型Get<T>和Set<T>扩展方法并非ASP.NET Core框架核心自带,需要安装Microsoft.AspNetCore.Session NuGet包:
- 使用Package Manager控制台:
Install-Package Microsoft.AspNetCore.Session - 或者通过Visual Studio的NuGet包管理器搜索并安装该包。
2. 手动实现Session扩展方法(可选)
如果不想额外安装包,可以自己实现序列化/反序列化的扩展方法,使用System.Text.Json处理对象转换:
using Microsoft.AspNetCore.Http; using System.Text.Json; public static class SessionExtensions { public static void Set<T>(this ISession session, string key, T value) { session.SetString(key, JsonSerializer.Serialize(value)); } public static T Get<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default : JsonSerializer.Deserialize<T>(value); } }
将这个类放在项目的合适目录(比如Extensions文件夹),然后在控制器中引入对应的命名空间即可使用。
3. 修正代码中的拼写错误
注意到控制器代码中orderDetails.PorductId存在拼写错误,应改为orderDetails.ProductId,避免后续订单详情关联商品时出现数据错误。
内容的提问来源于stack exchange,提问作者ha33
相关产品推荐
相关产品推荐

