Retrieve ASP.NET Profile from App_Code, asmx Web Services

Its most very likely that you will be using the Membership, Roles and Profile providers provided by the .NET framework. It has been well designed and is very easy to use.

When you are in the .aspx.cs (basically the class that inherits from System.Web.UI.Page) you can easily access Profile class and get the profile for a particular user by using the following syntax.

ProfileCommon profile=Profile.GetUser("username");

But if you are creating some huge enterprise level applications, you will soon arrive to a problem where you can no longer the access the Profile. This happens if you want to call your profile from .cs files App_Code or library files (.dll) including webservices such as .asmx.

This problem can be solved by accessing the ProfileBase class in System.Web.Profile namespace.

ProfileCommon profile = (ProfileCommon)ProfileBase.Create("username", true);

Even though the method called is Create, it doesn’t create a new Profile for the user. If the profile already exists it retrieves it. Second parameter indicates whether the user is authenticated or anonymous. true if the user is authenticated else false to indicate anonymous.