Get CustommerContext in WebApi


I need to get some user info in a commerce project in an ApiController class. This is in a library project, so I will not know what kind of a provider a consuming project will have implemented.
If I understand it corectly, I need to get CustomerContact to get commerce user data.
Problem is I cannot use Current user ID, because it is WebApi.
I can get EpiserverProfile, because I have userName in Request payload, but what about Anonymous users? I would want to get Icart of those users, will that be possible?

Mar 12, 2020 14:45

Hi Gabel,

I have used MVC controller to make the API request in the current project instead of using ApiController class and able to get cart info for the anonymous user also

Please try the below steps.

Step 1: Add below reference into the library project

using EPiServer.Commerce.Order;
using Mediachase.Commerce.Customers;
using Mediachase.Commerce.Orders;

Step 2: Inject IOrderRepository instance to load the cart.

private readonly IOrderRepository _orderRepository;
var cart = _orderRepository.LoadOrCreateCart<ICart>(CustomerContext.Current.CurrentContactId, "Default");

 Hope it will work for you!

Edited, Mar 13, 2020 10:22

Hi Sanjay,
What do you mean that you did not used ApiController? Then how did you handle your request?
Also, CustomerContext.Current is for  current contect, witch in case of WebApi is not the user that is browsing the page, is it?

Mar 13, 2020 13:38

Hi Gabel,

We have added some settings in web.config handler level which is allowed to call MVC controller similar to APIController. We are using same project for Frontend (react) and Backend (MVC controller) to communicate but in your case, you should need to send data in the request of endpoint for the retrieving cart details if the previous solution is not working.

Edited, Mar 13, 2020 14:04
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.