Sample ASP.NET Core 6.0 reference application, powered by Microsoft, demonstrating a layered application architecture with monolithic deployment model. Download the eBook PDF from docs folder.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

60 lines
1.9 KiB

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopWeb.Infrastructure.Identity;
using Microsoft.eShopWeb.Web.Interfaces;
using Microsoft.eShopWeb.Web.Pages.Basket;
using Microsoft.eShopWeb.Web.ViewModels;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.Web.Pages.Shared.Components.BasketComponent
{
public class Basket : ViewComponent
{
private readonly IBasketViewModelService _basketService;
private readonly SignInManager<ApplicationUser> _signInManager;
public Basket(IBasketViewModelService basketService,
SignInManager<ApplicationUser> signInManager)
{
_basketService = basketService;
_signInManager = signInManager;
}
public async Task<IViewComponentResult> InvokeAsync(string userName)
{
var vm = new BasketComponentViewModel();
vm.ItemsCount = (await GetBasketViewModelAsync()).Items.Sum(i => i.Quantity);
return View(vm);
}
private async Task<BasketViewModel> GetBasketViewModelAsync()
{
if (_signInManager.IsSignedIn(HttpContext.User))
{
return await _basketService.GetOrCreateBasketForUser(User.Identity.Name);
}
string anonymousId = GetAnnonymousIdFromCookie();
if (anonymousId == null)
return new BasketViewModel();
return await _basketService.GetOrCreateBasketForUser(anonymousId);
}
private string GetAnnonymousIdFromCookie()
{
if (Request.Cookies.ContainsKey(Constants.BASKET_COOKIENAME))
{
var id = Request.Cookies[Constants.BASKET_COOKIENAME];
if (Guid.TryParse(id, out var _))
{
return id;
}
}
return null;
}
}
}