This one is complicated. I have a following middleware in my Program.cs:
app.UseMiddleware<LowercaseUrlMiddleware>();
app.UseHttpsRedirection();
app.UseWebOptimizer();
app.UseStaticFiles();
app.UseRouting();
app.UseRequestLocalization();localization
app.UseSession();
app.UseMiddleware<SessionMiddleware>();//THIS!!!!
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
app.Run();
Notice SessionMiddleware. That's where problems arise.
Code of SessionMiddleware:
namespace CCUI.Middleware
{
public class SessionMiddleware
{
private readonly RequestDelegate _next;
public SessionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var excludedExtensions = new[] { ".css", ".js", ".png", ".jpg", ".gif" };
var pathValue = context.Request.Path.Value?.ToLower();
var queryValue = context.Request.QueryString.Value;
var isAjaxRequest = false;//context.Request.Headers["Content-Type"].ToString().Contains("application/json");
if ((string.IsNullOrEmpty(queryValue) || !queryValue.Contains("handler=")) && !isAjaxRequest &&
(pathValue == null || !excludedExtensions.Any(ext => pathValue.EndsWith(ext))))
{
Guid parsedGuid;
// Checking for the VisitorGUID cookie
if (!context.Request.Cookies.TryGetValue("CustomClosetsVisitorGUID", out var visitorGuid) ||
string.IsNullOrWhiteSpace(visitorGuid) ||
!Guid.TryParse(visitorGuid, out parsedGuid))
{
// Generate a new GUID
visitorGuid = Guid.NewGuid().ToString();
}
// Set (or reset) the cookie with the GUID value and extend its expiration
context.Response.Cookies.Append("CustomClosetsVisitorGUID", visitorGuid);
// Store the VisitorGUID in the session -- this line causes problems
context.Session.SetString("VisitorGUID", visitorGuid);
}
await _next(context);
}
}
}
Notice var isAjaxRequest = false -- this is for testing.
When isAjaxRequest set correctly -- all good. If not, then IN OTHER PARTS of code that read/set session session does not get set. We have /get-cart endpoint in CartController that sets cart guid to session. But after reload it is not set.
It looks like because of concurrency session values are not getting persisted. I read that session is set on request end, so maybe that get obrupted.
So I ajax requests are filtered out in this middleware, then AJAX request to /get-cart works correctly and value persists.... Thoughts?
namespace CCUI.Controllers;
[ApiController]
[Route("api/shopping-cart")]
public class CartController(IShoppingCartService _cartService, ISearchService _searchService, IProductsService _productService, AppConfiguration _appConfig) : ControllerBase
{
[HttpGet("cart")]
public async Task<IActionResult> GetShoppingCart()
{
ShoppingCart? cart = null;
String? guid = HttpContext.Session.GetString("ShoppingCartGuid");
if (!string.IsNullOrWhiteSpace(guid))
{
cart = await _cartService.GetShoppingCartByGUIDAsync(guid);
}
if (cart == null)
{
cart = await _cartService.CreateNewShoppingCartAsync(_appConfig.SalesChannelId, null);
HttpContext.Session.SetString("ShoppingCartGuid", cart.Guid.ToString());
}
return Ok(cart);
}
}
isAjaxRequest = false, then you find all the session value is not persisted(you couldn't get it from controller)? But if you set theisAjaxRequest = true, then you could get the set session value inside the controller?