How to get Current Customer in middleware?

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
3 years ago
[nopcommerce 4.30]
Hi all, i have register a custom middleware (for custom authentication user) in NopCommonStartup/Configure.

In my custom middleware i have inject IWorkContext.

When i set debug in my custom middleware and some function in controller have use IWorkContext.
The _workContext.CurrentCustomer  in my custom middleware and function in controller is diffirent.
In my custom middleware: the _workContext.CurrentCustomer is last guest access.
In other function: exactly current user i login.
How can i get exacly current user in my custom middleware?
Tks for reading. Sorry about my terrible english.
3 years ago
Are trying to access _workContext.CurrentCustomer before it is initialised ?
Or when you  access _workContext.CurrentCustomer it shows as a Guest ?
Is anyone logged in ?
3 years ago
Set a breakpoint in Nop.Web.Framework\WebWorkContext.cs in the CurrentCustomer method to see which customer is getting accessed.  It sounds like the middleware may be grabbing a different cached cookie value, or otherwise inserting a new guest:


//whether there is a cached value
if (_cachedCustomer != null)
    return _cachedCustomer;

................................

if (customer == null || customer.Deleted || !customer.Active || customer.RequireReLogin)
{
    //get guest customer
    var customerCookie = GetCustomerCookie();
    if (!string.IsNullOrEmpty(customerCookie))
   {
       if (Guid.TryParse(customerCookie, out Guid customerGuid))
       {
           //get customer from cookie (should not be registered)
          var customerByCookie = _customerService.GetCustomerByGuid(customerGuid);
          if (customerByCookie != null && !customerByCookie.IsRegistered())
              customer = customerByCookie;
       }
   }
}

if (customer == null || customer.Deleted || !customer.Active || customer.RequireReLogin)
{
    //create guest if not exists
    customer = _customerService.InsertGuestCustomer();
}


You can use your browser DevTools to compare cookie values for the GUID.
3 years ago
tks all for reply my question. Happy weekend <3
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.