在ASP MVC你不必爲您的網站在web.config文件中定義的屬性生成的配置文件對象。可以通過控制器方法訪問的屬性Profile
的類型爲ProfileBase
(see msdn),並且不包含您的自定義配置文件屬性的強類型屬性。您也可能知道,在請求開始時爲登錄用戶加載此配置文件,並且在請求結束時保存所有更改。
有different ways你可以工作ProfileBase
類。最常用的的是:
- 直接使用的ProfileBase類
- 創建一個派生自定義配置文件類。
當直接使用ProfileBase
時,您需要使用控制器方法中的實例或獲取給定用戶名的實例。然後,您應該使用索引器訪問配置文件屬性。比方說,你的控制器的方法收到類型的usermodel的對象,其中包含如電子郵件和BadgerName您的用戶數據,那麼你可以這樣寫代碼:
//Getting the instance from the controller property:
ProfileBase profile = this.Profile; //or even: this.HttpContext.Profile
//You can also get the profile for a given existing user.
ProfileBase profile = ProfileBase.Create(userModel.Name);
//Then update properties using indexer
profile["Email"] = userModel.Email;
profile["BadgerName"] = userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
但是如果從ProfileBase
創建一個派生類,你會最終以與你原先想要的相同的方式使用你的班級。您將基本建立與內部訪問使用ProfileBase索引強類型屬性的包裝類(方法的總結here):
public class MyCustomProfile : ProfileBase
{
public string Email
{
get { return base["Email"] as string; }
set { base["Email"] = value; }
}
public string BadgerName
{
get { return base["BadgerName"] as string; }
set { base["BadgerName"] = value; }
}
//If needed, you can provide methods to recover profiles
//for the logged in user or any user given its user name
public static MyCustomProfile GetCurrent()
{
return Create(Membership.GetUser().UserName) as MyCustomProfile;
}
public static MyCustomProfile GetProfile(string userName)
{
return Create(userName) as MyCustomProfile;
}
}
如果使用這個選項,你還需要確保<profile>
元素在web.config中有inherits
屬性設置爲自定義模型類:
<profile enabled="true" defaultProvider="DefaultProfileProvider" inherits="yourNamespace.MyCustomProfile">
有了這個代碼和配置到位,您可以開始使用您的自定義配置文件類由要麼恢復用戶配置文件yourselve或鑄造控制器配置文件屬性到您的自定義類:
//Cast the Profile property of the controller to your custom class
MyCustomProfile profile = this.Profile as MyCustomProfile // or even: HttpContext.Profile as MyCustomProfile
//You could also manually load the profile for given an user name
profile = MyCustomProfile.GetProfile(userModel.Name);
//Or even manually load the profile for the logged in user
profile = MyCustomProfile.GetCurrent();
//Now get/set the profile properties using the strongly typed properties of your class
profile.Email= userModel.Email;
profile.BadgerName= userModel.BadgerName;
//Manually save changes
//(Can be skipped for the profile automatically loaded in the Controller)
profile.Save();
希望這有助於!
很好的答案,謝謝。 – orangesherbert 2013-02-28 23:24:05