如何在库类中使用Profile.GetProfile()?

时间:2009-09-18 21:02:38

标签: c# asp.net membership profile

我无法弄清楚如何在库类中使用Profile.GetProfile()方法。 我尝试在Page.aspx.cs中使用此方法,它运行得很好。

如何在page.aspx.cs中创建一个适用于类库的方法。

3 个答案:

答案 0 :(得分:2)

在ASP.NET中,Profile是HttpContext.Current.Profile属性的一个钩子,它返回一个动态生成的对象,类型为ProfileCommon,派生自System.Web.Profile.ProfileBase

ProfileCommon显然包含一个GetProfile(字符串用户名)方法,但你不会在MSDN中找到它正式记录(并且它不会出现在visual studio中的intellisense中),因为大多数ProfileCommon类是在你的ASP.NET应用程序中动态生成的编译(属性和方法的确切列表将取决于如何在web.config中配置'配置文件')。 GetProfile() does get a mention on this MSDN page,所以它似乎是真实的。

也许在您的库类中,问题是没有拾取来自web.config的配置信息。您的库类是包含Web应用程序的Solultion的一部分,还是您只是单独处理库?

答案 1 :(得分:1)

您是否尝试过将System.Web.dll的引用添加到您的类库中,然后:

if (HttpContext.Current == null) 
{
    throw new Exception("HttpContext was not defined");
}
var profile = HttpContext.Current.Profile;
// Do something with the profile

答案 2 :(得分:0)

您可以使用ProfileBase,但会失去类型安全性。您可以通过仔细的转换和错误处理来缓解这种情况。

    string user = "Steve"; // The username you are trying to get the profile for.
    bool isAuthenticated = false;

        MembershipUser mu = Membership.GetUser(user);

        if (mu != null)
        {
            // User exists - Try to load profile 

            ProfileBase pb = ProfileBase.Create(user, isAuthenticated);

            if (pb != null)
            {
                // Profile loaded - Try to access profile data element.
                // ProfileBase stores data as objects in a Dictionary 
                // so you have to cast and check that the cast succeeds.

                string myData = (string)pb["MyKey"];

                if (!string.IsNullOrWhiteSpace(myData))            
                {
                    // Woo-hoo - We're in data city, baby!
                    Console.WriteLine("Is this your card? " + myData);
                }
            }        
        }