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

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

如何创建一个在page.aspx.cs中工作的方法,在类库中工作。

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

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

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

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

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

您可以使用ProfileBase,但是会丢失类型安全性。 您可以通过仔细的转换和error handling来缓解这种情况。

  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); } } }