I writing a shop in .Net Core 3, and I try to use Session for save Cart items, but an exception is throw [closed]

青春壹個敷衍的年華 提交于 2020-01-26 04:44:05

问题


this is my controller and session cart . in first step i want to save cart items to session and the save to database.this programe writing by mvc core 3. i learn this code from Apress.Pro.ASP.NET.Core.MVC.6th.Edition. teacher write code to core2 but i am trying to write core3.0.

public class CartController : Controller
{
    private readonly IProductRepository repository;
    private Cart _cart;
    public CartController(IProductRepository repo, Cart cart)
    {
        repository = repo;
        _cart = cart;
    }

    public IActionResult Index(string returnurl)
    {
        ViewBag.ReturnUrl = returnurl;
        //return View(GetCart());
        return View(_cart);
    }
    public IActionResult AddToCart(int ProductID,string returnUrl)
    {
        Product product = repository.GetById(ProductID);
        if (product != null)
        {
            //Cart cart = GetCart();
            //cart.AddItem(product, 1);
            //SaveCart(cart);
            _cart.AddItem(product, 1);
        }
        return RedirectToAction("Index", new { returnUrl });
    }
    public IActionResult RemoveFromCart(int ProductID, string returnUrl)
    {
        Product product = repository.GetById(ProductID);
        if (product != null)
        {
            //Cart cart = GetCart();
            //cart.RemoveLine(product);
            //SaveCart(cart);
            _cart.RemoveLine(product);
        }
        return RedirectToAction("Index", new { returnUrl });
    }
    //private Cart GetCart()
    //{
    //    Cart cart = HttpContext.Session.GetJson<Cart>("Cart") ?? new Cart();
    //    return cart;
    //}
    //private void SaveCart(Cart cart)
    //{
    //    HttpContext.Session.SetJson("Cart", cart);
    //}
}

and

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddSession();
        services.AddMvc();

        services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(configuration.GetConnectionString("IctShop")));
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<Cart>(sp => SessionCart.GetCart(sp));
        services.AddScoped<IProductRepository, EFProductRepository>();
        //services.AddControllersWithViews();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePages();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSession();
        app.UseRouting();

        app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });



        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

and

public  class SessionCart : Cart
{
    public static Cart GetCart(IServiceProvider services)
    {
        ISession session = services.GetRequiredService<IHttpContextAccessor>()?
        .HttpContext.Session;
        SessionCart cart = session?.GetJson<SessionCart>("Cart")
        ?? new SessionCart();
        cart.Session = session;
        return cart;
    }
    [JsonIgnore]
    public ISession Session { get; set; }
    public override void AddItem(Product product, int quantity)
    {
        base.AddItem(product, quantity);
        Session.SetJson("Cart", this);
    }
    public override void RemoveLine(Product product)
    {
        base.RemoveLine(product);
        Session.SetJson("Cart", this);
    }
    public override void Clear()
    {
        base.Clear();
        Session.Remove("Cart");
    }
}

and error pic is:

来源:https://stackoverflow.com/questions/59751413/i-writing-a-shop-in-net-core-3-and-i-try-to-use-session-for-save-cart-items-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!