0

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);
    }

}


2
  • Do you mean if you set the isAjaxRequest = false , then you find all the session value is not persisted(you couldn't get it from controller)? But if you set the isAjaxRequest = true, then you could get the set session value inside the controller? Commented Sep 18, 2024 at 13:37
  • @BrandoZhang hmmm... not sure. if isAjaxRequest = false, then i GET ShoppingCartGuid - it is null, i create new one, set to session, reload the page, it is null again... Now when you ask I am not sure - the Set does not work, or the Get. Commented Sep 18, 2024 at 13:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.