|
|
|
@ -3,7 +3,6 @@ using System.Threading.Tasks; |
|
|
|
using EShopOnAbp.BasketService.Services; |
|
|
|
using EShopOnAbp.Shared.Hosting.AspNetCore; |
|
|
|
using Microsoft.AspNetCore.Http; |
|
|
|
using Microsoft.Extensions.Logging; |
|
|
|
using Volo.Abp.DependencyInjection; |
|
|
|
|
|
|
|
namespace EShopOnAbp.PublicWeb.ServiceProviders |
|
|
|
@ -13,34 +12,40 @@ namespace EShopOnAbp.PublicWeb.ServiceProviders |
|
|
|
private HttpContext HttpContext => _httpContextAccessor.HttpContext; |
|
|
|
|
|
|
|
private readonly IHttpContextAccessor _httpContextAccessor; |
|
|
|
private readonly ILogger<UserBasketProvider> _logger; |
|
|
|
private readonly IBasketAppService _basketAppService; |
|
|
|
|
|
|
|
public UserBasketProvider( |
|
|
|
IHttpContextAccessor httpContextAccessor, |
|
|
|
ILogger<UserBasketProvider> logger, |
|
|
|
IBasketAppService basketAppService) |
|
|
|
{ |
|
|
|
_httpContextAccessor = httpContextAccessor; |
|
|
|
_logger = logger; |
|
|
|
_basketAppService = basketAppService; |
|
|
|
} |
|
|
|
|
|
|
|
public virtual async Task<BasketDto> GetBasketAsync() |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
// Get anonymous user id from cookie
|
|
|
|
HttpContext.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, |
|
|
|
out string anonymousUserId); |
|
|
|
var anonymousUserId = await GetAnonymousUserId(); |
|
|
|
|
|
|
|
return await _basketAppService.GetAsync(Guid.Parse(anonymousUserId)); |
|
|
|
} |
|
|
|
catch (Exception ex) |
|
|
|
return await _basketAppService.GetAsync(Guid.Parse(anonymousUserId)); |
|
|
|
} |
|
|
|
|
|
|
|
// Get anonymous user id from cookie
|
|
|
|
private async Task<string> GetAnonymousUserId() |
|
|
|
{ |
|
|
|
HttpContext.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, out string anonymousUserId); |
|
|
|
// Generate guid for anonymous user id and set to cookie for 14 days
|
|
|
|
if (string.IsNullOrEmpty(anonymousUserId)) |
|
|
|
{ |
|
|
|
_logger.LogError(ex, ex.Message); |
|
|
|
return null; |
|
|
|
anonymousUserId = Guid.NewGuid().ToString(); |
|
|
|
HttpContext.Response.Cookies.Append(EShopConstants.AnonymousUserClaimName, anonymousUserId, |
|
|
|
new CookieOptions |
|
|
|
{ |
|
|
|
SameSite = SameSiteMode.Lax, |
|
|
|
Expires = DateTimeOffset.UtcNow.AddDays(14) |
|
|
|
}); |
|
|
|
} |
|
|
|
|
|
|
|
return anonymousUserId; |
|
|
|
} |
|
|
|
} |
|
|
|
} |