In today’s guide, we are going to go over everything you will need to be able to check if a current request matches your visitor group. In order to do this we will be using the IVisitorGroupRepository. If you haven’t come across this API yet, then I would recommend reading this first, How To Create An Episerver Visitor Group Via Code
In order to check if the current request matches a visitor group, you will need to look at the VisitorGroupHelper. Unfortunately, the Visitor Group Helper does not have an interface, which means you have to new it up in your code. This makes unit testing a little bit harder. If you want to test your code, then I would recommend creating a very basic wrapper for the class.
VisitorGroupHelper has one method, IsPrincipalInGroup which takes in an IPrinciple and a role. The role needs to match the visitor group name, so for example if your visitor group is called ‘Example Visitor Group’ that is what you pass in.
var visitorGroupGuidId = new Guid("e7666be5-3a81-4a0a-a551-a0c857cbf629"); var visitorGroupRepository = ServiceLocator.Current.GetInstance<IVisitorGroupRepository>(); var user = HttpContext.Current.User; var vgHelper = new VisitorGroupHelper(visitorGroupGuidId); var visitorGroup = visitorGroupRepository.Load(visitorGroupGuidId); var allowedAccess = vgHelper.IsPrincipalInGroup(user, visitorGroup.Name);
The code is pretty straight forward, we load the visitor group we are interested in from the repository via the Guid name. In my example, I’m using the code from How To Create A Visitor Group Selection Factory to store the Id.