I am using this article to implement ASP.NET SQLMembership Profile Provider in my ASP.NET 4.0 Web Application project (NOT website project). I am using Forms authentication. On my admin page I need to display the profile info of all the users. But for some reason, the following code is always returning the profile of the current user instead of each user whose username is provided:
ProfileInfoCollection oProfInfoColl = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
string sUserName = "";
foreach (ProfileInfo oPi in oProfInfoColl)
{
sUserName = oPi.UserName;
UserProfile oPc = UserProfile.GetUserProfile(sUserName);
oDataTbl.Rows.Add(new string[] { oPc.Company, oPc.FirstName, oPc.LastName, sUserName, Roles.GetRolesForUser(sUserName)[0] });
}
In the above code oPi.UserName
correctly returns the username of each user but GetUserProfile(sUserName)
always returns the profile of the currently logged in user.
When I display the Profile properties (FirstName, LastName etc.) on the page I see that these properties are for the currently logged in user in each row even though the UserName and roles of each users are displayed correctly in each row for the specified user. Please note that the username and the roles are not coming from the profile.
My UserProfile custom class is:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
namespace WebAppName
{
public class UserProfile : ProfileBase
{
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
[SettingsAllowAnonymous(true)]
public string Company
{
get
{
return (string)HttpContext.Current.Profile.GetPropertyValue("Company");
}
set
{
HttpContext.Current.Profile.SetPropertyValue("Company", value);
}
}
[SettingsAllowAnonymous(true)]
public string FirstName
{
get
{
return (string)HttpContext.Current.Profile.GetPropertyValue("FirstName");
}
set
{
HttpContext.Current.Profile.SetPropertyValue("FirstName", value);
}
}
[SettingsAllowAnonymous(true)]
public string LastName
{
get
{
return (string)HttpContext.Current.Profile.GetPropertyValue("LastName");
}
set
{
HttpContext.Current.Profile.SetPropertyValue("LastName", value);
}
}
}
}
My web.config file has following Profile section:
<profile inherits="WebAppName.UserProfile" enabled="true" defaultProvider="ProjectNameSqlProvider" automaticSaveEnabled="true">
<providers>
<clear />
<add name="ProjectNameSqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="MyConnectionString" applicationName="ProjectName" />
</providers>
</profile>