ライブラリクラスでProfile.GetProfile()を使用する方法?
-
22-07-2019 - |
質問
ライブラリクラスで Profile.GetProfile()
メソッドを使用する方法がわかりません。
Page.aspx.csでこのメソッドを使用してみましたが、完全に機能しました。
page.aspx.csで機能するメソッドをクラスライブラリで機能させるにはどうすればよいですか。
解決
ASP.NETでは、プロファイルは HttpContext.Current.Profile プロパティ。 System.Web.Profile.ProfileBase 。
ProfileCommonには明らかにGetProfile(string username)メソッドが含まれていますが、ASP.NETアプリケーションのほとんどのProfileCommonクラスが動的に生成されるため、MSDNで公式に文書化されていることはわかりません(Visual Studioのintellisenseには表示されません)コンパイルされます(プロパティとメソッドの正確なリストは、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を使用できますが、タイプセーフが失われます。キャストとエラー処理を慎重に行うことで、これを軽減できます。
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);
}
}
}