Asp.Net MVC 中的 Profile Provider





4.00/5 (1投票)
由于在 Asp.Net MVC 中如何实现 Profile 的相关信息非常少,我想分享我实现此功能的解决方案。为了演示
由于在 Asp.Net MVC 中如何实现 Profile 的相关信息非常少,我想分享我实现此功能的解决方案。
为了演示的目的,假设您只想存储用户的名字和姓氏。
首先,我创建了一个 "UserProfile" 类,它继承自 "System.Web.Profile.ProfileBase",并按如下方式实现:
public class UserProfile : ProfileBase
{
[SettingsAllowAnonymous(false)]
public string FirstName
{
get { return base["FirstName"] as string; }
set { base["FirstName"] = value; }
}
[SettingsAllowAnonymous(false)]
public string LastName
{
get { return base["LastName"] as string; }
set { base["LastName"] = value; }
}
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
}
完成之后,我确保我的 Profile Provider 在我的 web.config 中设置正确(注意我是如何从上面的类继承的)
<profile inherits="Krok.Core.BusinessLogic.Models.Account.UserProfile">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
由于我喜欢保持逻辑分离,并且只使用强类型视图模型,所以我单独创建了一个视图模型类
public class UserProfileViewModel
{
[DisplayName("First Name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[DataType(DataType.Text)]
public string LastName { get; set; }
}
现在,我创建了两个 action 方法,一个用于显示用户的 profile,一个用于编辑它
[Authorize]
public ViewResult Profile()
{
UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
var model = new UserProfileViewModel
{
FirstName = profile.FirstName,
LastName = profile.LastName
};
return View(model);
}
[HttpPost]
[Authorize]
public ActionResult Profile(UserProfileViewModel model)
{
if (ModelState.IsValid)
{
UserProfile profile = UserProfile.GetUserProfile(User.Identity.Name);
profile.FirstName = model.FirstName;
profile.LastName = model.LastName;
profile.Save();
return RedirectToRoute("Account.Profile");
}
return View(model);
}
现在,您显然只需要创建两个视图,都是强类型的 (UserProfileViewModel)
希望这能帮助需要在 Asp.Net MVC 应用程序中实现 Profile 的人。