A
A
Alexxxey_enot2021-04-09 09:56:21
ASP.NET
Alexxxey_enot, 2021-04-09 09:56:21

Is there an error somewhere in the code?

606ff893f32f8348173821.pngThis error is detected in the code when clicking on the "add to cart" button or when specifying the path of the controller
606ff9c811fdd520375298.png

public class ShopCart
    {
        private readonly AppDBContent appDBContent;
        public ShopCart(AppDBContent appDBContent)
        {
            this.appDBContent = appDBContent;
        }
        public string ShopCartId { get; set; }      

        public List<ShopCartItem> listShopItems { get; set; }

        public static ShopCart GetCart(IServiceProvider services)
        {
            ISession session = services.GetRequiredService<IHttpContextAccessor>()?.HttpContext.Session;
            var context = services.GetService<AppDBContent>();
            string shopCartId = session.GetString("CartId") ?? Guid.NewGuid().ToString();

            session.SetString("CartId", shopCartId);

            return new ShopCart(context) { ShopCartId = shopCartId };
        }
        public void AddToCart(Car car)
        {
            appDBContent.ShopCartItem.Add(new ShopCartItem {
            ShopCartId = ShopCartId,
            car = car,
            price = car.price
            });

            appDBContent.SaveChanges();
        }

        public List<ShopCartItem> getShopItems()
        {
            return appDBContent.ShopCartItem.Where(c => c.ShopCartId == ShopCartId).Include(s => s.car).ToList();
        }
    }

public class ShopCartController : Controller
    {
        private readonly IAllCars _carRep;
        private readonly ShopCart _shopCart;
        public ShopCartController(IAllCars carRep, ShopCart shopCart)
        {
            _carRep = carRep;
            _shopCart = shopCart;
        }
        public ViewResult Index()
        {
            var items = _shopCart.getShopItems();
            _shopCart.listShopItems = items;

            var obj = new ShopCartViewModel
            {
                shopCart = _shopCart
            };
            return View(obj);
        }
        public RedirectToActionResult addToCart(int id)
        {
            var item = _carRep.Cars.FirstOrDefault(i => i.id == id);

            if(item != null)
            {
                _shopCart.AddToCart(item);
            }
            return RedirectToAction("Index");
        }
    }

@model ShopCartViewModel
<div class="container">
    @foreach(var el in Model.shopCart.listShopItems)
            {
                <div class="alert alert-warning mt-3">
                    <b>Автомобиль:</b>@el.car.name<br/>
                    <b>Цена:</b>@el.car.price.ToString("c")
                </div>
            }
    <hr />
    <a class="btn btn-danger" asp-controller="Order" asp-action="Checkout">Оплатить</a>
</div>

public class Startup
    {
        private IConfigurationRoot _confSting;
        public Startup(IWebHostEnvironment hostEnv)
        {
            _confSting = new ConfigurationBuilder().SetBasePath(hostEnv.ContentRootPath).AddJsonFile("dbsettings.json").Build();

        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)  
        {
            services.AddDbContext<AppDBContent>(options => options.UseSqlServer(_confSting.GetConnectionString("DefaultConnection")));
            services.AddControllersWithViews();
            services.AddTransient<IAllCars, CarRepository>();
            services.AddTransient<ICarsCategory, CategoryRepository>();
            services.AddTransient<IAllOrders, OrdersRepository>();
            services.AddTransient<ShopCart>();

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped(sp => ShopCart.GetCart(sp));
            services.AddSession();

        }

        // 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();
            }
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                   name: "categoryFilter",
                   pattern: "Car/{action}/{category?}", defaults: new { Controller="Car", action="List"});
            });
            app.UseStaticFiles();

          

            
            using (var scope = app.ApplicationServices.CreateScope())
            {
                AppDBContent content = scope.ServiceProvider.GetRequiredService<AppDBContent>();
                DBObjects.Initial(content);
            }

        }
    }

https://github.com/Alexey411/asp.netcoremvc

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Ross Man, 2021-04-10
@Alexxxey_enot

app.UseSession();
Before app.UseEndpoints

C
cicatrix, 2021-04-09
@cicatrix

Well, how about google the error?
Startup.cs show

R
Roman, 2021-04-09
@yarosroman

HttpContext is available as a controller property, why get it via DI? just write HttpContext.Session.
var context = services.GetService<AppDBContent>();
What for? why not just register in the container and let DI do its job. How will you test then?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question