I have been trying to access the current HttpContext in a partial router so that I can use the user and session data associated with this current context.I am using IHttpContextAccessor with DI in the same way I am within controllers, and although this is showing a context with user information, it isn't the correct context.
The router is of type EPiServer.Core.Routing.IPartialRouter<Page, PartialContent>In CMS 11 the same code worked and we could access the correct context in the router, but in CMS 12 and .net core this isn't working.Any help/explanation is appreciated! :)
What version of 12 are you on?
Can you elaborate on "it isn't the correct context." and the difference you are seeing with injected HttpContext with Controllers vs PartialRouter
I have the same problem. In controllers the User.Identity.Name is correct on a logged in user
But in a PartialRouter the Name property is null (the Identity object is an anonymous user).
So I can't fetch the current user via UserManager.GetUserAsync()
Just guessing, since I can't run your code. But could it be that these partial routers are executed before the authentication handler? If so, then you cannot access the correct user identity.
If I may ask, why do you need to route content based on the current user?
We fetch data from a CRM so we have for example:
Where /companyname/ is a virutal page with information fetched from the CRM, but we need the logged in user (which has a company property) in order to fetch data from the CRM.
But in the end i scrapted IPartialRouter since it didn't work as intended in epi 12 (see my post here: https://world.optimizely.com/forum/developer-forum/cms-12/thread-container/2023/8/partial-routing-not-working-custom-controller-not-being-executed-/ ) and used this instead and moved all logic to the original page controller (where I can access HttpContext.User.
Sounds like a reasonable requirement, Alexander.
However, to do that you would have to put UseRouting() after UseAuthentication() in the Startup.cs file. But that goes against the official MS recommendation. If you swap them around you cannot use authorization policies on the controller.
What about if the partial router just takes the requested "companyname" route value and passes it to the controller? Then the controller fetches that content from the CRM, provided the User identity matches the requested company name value.
That's how I solved it, but without having a IPartialRouter, via MapTemplate<> :). Worked like a charm (even though I feel that it would be best to have a separate class for the virtual pages logic instead of having that in the base page controller).