本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (25) 建立購物車系統 - 8
在WebMvc的Models資料夾新增CartModels,再新增Cart.cs和CartItem.cs,代表透過Service傳遞的購物車資料模型:
using System;
using System.Collections.Generic;
using System.Linq;
namespace WebMvc.Models.CartModels
{
public class Cart
{
public List<CartItem> Items { get; set; } = new List<CartItem>();
public string BuyerId { get; set; }
public decimal Total()
{
return Math.Round(Items.Sum(x => x.UnitPrice * x.Quantity), 2);
}
}
}
namespace WebMvc.Models.CartModels
{
public class CartItem
{
public string Id { get; set; }
public string ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public decimal OldUnitPrice { get; set; }
public int Quantity { get; set; }
public string PictureUrl { get; set; }
}
}
在WebMvc的Services資料夾新增IAuthService介面和實作的AuthService,主要是將Identity的User解析出Claims並回傳相關的欄位:
using System.Security.Principal;
namespace WebMvc.Services
{
public interface IAuthService<T>
{
T Get(IPrincipal principal);
}
}
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using WebMvc.Models;
namespace WebMvc.Services
{
public class AuthService : IAuthService<ApplicationUser>
{
public ApplicationUser Get(IPrincipal principal)
{
if (principal is ClaimsPrincipal claims)
{
var user = new ApplicationUser()
{
Email = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? ""
};
return user;
}
throw new ArgumentException(message: "the principal must be a claimsprincipal", paramName: nameof(principal));
}
}
}
在WebMvc專案的Models新增ApplicationUser.cs,並繼承Microsoft.AspNetCore.Identity的IdentityUser
在WebMvc專案的Services新增ICartService,所有購物車相關的功能會透過此服務:
using System.Collections.Generic;
using System.Threading.Tasks;
using WebMvc.Models;
using WebMvc.Models.CartModels;
namespace WebMvc.Services
{
public interface ICartService
{
Task<Cart> GetCartAsync(ApplicationUser user);
Task AddItemToCartAsync(ApplicationUser user, CartItem product);
Task<Cart> UpdateCartAsync(Cart cart);
Task<Cart> SetQuantitiesAsync(ApplicationUser user, Dictionary<string, int> quantities);
Task ClearCartAsync(ApplicationUser user);
}
}