MVC 5 Identity 2.0在登录时显示配置文件完成
本文关键字:显示 配置文件 登录 Identity MVC | 更新日期: 2023-09-27 18:03:57
使用MVC 5和Identity 2.0,我添加自定义属性到ApplicationUserClass
,如FirstName
, LastName
, Address
。这些将是数据库中的新字段。当用户注册到应用程序时,他/她将只输入电子邮件地址和密码。在他们注册后,他们登录,我想强迫他们完成他们的个人资料,或者至少每次他们登录时,他们应该被重定向到个人资料完成页面,在那里他们可以提到FirstName, Lastname和Address。他们完成配置文件后,他们将不会被重定向到完成配置文件页面,每次他们登录。
类似:
if UserProfile != Completed
go to CompleteProfilePage
else
go to MainPage
您可以尝试全局过滤器。这将不允许您的用户通过手动修改URL来绕过检查。
public class ProfileCompletionCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//this will prevent redirect for still unauthenticated users
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
return;
//replace these to actual values of your profile completion action and controller
string actionOfProfilePage = "Index";
string controlerOfProfilePage = "Home";
bool areWeAlreadyInProfilePage = filterContext.ActionDescriptor.ActionName == actionOfProfilePage
&& filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == controlerOfProfilePage;
if (areWeAlreadyInProfilePage) //this will prevent redirect loop
return;
bool isProfileComplete = false; //replace this with your custom logic
if (!isProfileComplete)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", controlerOfProfilePage },
{ "action", actionOfProfilePage }
});
}
}
}
要启用它,只需将此添加到FilterConfig.cs
filters.Add(new ProfileCompletionCheckAttribute());
在AccountController中像这样:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
像这样升级
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
UsersContext dbu = new UsersContext();
UserProfile usr = dbu.UserProfiles.Where(u => u.UserName == model.UserName).First();
if (usr.FirstName == null) return RedirectToAction("Profile", "Account");
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}