Umbraco Get Current Member or Member By ID
It seems like most pages when you Google for getting the current member or a member by id in Umbraco seem to be from back in 2010 or 2012, well things have changed since the businesslogic days and we're now in the world of Umbraco Services, how do we use them? Well, it's simpler than you think.
It used to be that you'd have to use the built in security methods such as Membership.GetUser(), or umbraco.cms.businesslogic.member.Member.GetCurrentMember(), but the former doesn't provide an Umbraco model and the latter, is horribly long, not very memorable and is also Obsolete!
Introducing the Membership Service:
You can access the membership service pretty easily by calling Services.Membership service and letting intellisense do the rest of the work for you by letting you know what else it offers, a quick example for getting e member by his/her username would be:
But that only works within a view/controller because they have an Umbraco context built in. For when you're not in a view or controller and you still need to access the services, it's a simple call to get the application context and suddenly they're all available to you:
A great example for why you might use the above is for you're writing a helper method/class that makes use of the membership service but you don't want to take it as a parameter.
Getting the current member:
To get the current member, you'll need to use a mixture of the membership service and the .NET Membership provider, but it's simple enough, just call it like so:
P.S: Just for the sake of a complete article, ApplicationContext is located in Umbraco.Core, so go ahead and add a using statement for that before calling it. Also Membership is located in System.Web.Security.
Published at 20 Jul 2018, 07:25 AM