我将 UserProfile 自定义字段 UserType 添加为字符串。我想更改login post method to get the value from UserType
并在TempData中传递此值。
这是我在AccountController上的代码:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
var context = new UsersContext();
var currentUser = Membership.GetUser(User.Identity.Name);
string username = currentUser.UserName;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var userType = user.UserType;
TempData["UserType"] = user.UserName; //Taking UserType from User Profile to validate in _Layout
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);
}
我对这个方法进行调试,这是我的信息:
> **On WebSecurity.Login()** I can see the UserName and Password.
> **Var CurrentUser** I can't get the value from User.Identity.Name
> **string Username** This error is displayed *Object reference not set to an instance of an object*. Application crash.
有人为此有一些解决方案吗? 我是ASP.NET的新手,但也许如果我实现自定义成员资格它会起作用,您怎么看?你能给我一些例子吗?谢谢你们。
此处的解决方案:
`[HttpPost] [使用AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model,string returnUrl) { if(ModelState.IsValid&&& WebSecurity.Login(model.UserName,model.Password,persistCookie:model.RememberMe)) { var context = new UsersContext(); var user = context.UserProfiles.Where(u => u.UserName == model.UserName); var userType = user.Select(m => m.UserType);
TempData["UserType"] = user.UserName; //Taking UserType from User Profile to validate in _Layout
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);
}`
答案 0 :(得分:0)
只是一个想法,万一我不能评论bcoz我的声誉,
为什么不直接使用model.UserName
而不是var currentUser = Membership.GetUser(User.Identity.Name);
这背后的原因是任何登录的人都将是当前的用户,您可以从数据库中检索其详细信息。
更新了
您可以使用
UserProfile User = udb.UserProfiles.Where(m => m.UserName == model.UserName).FirstOrDefault();
var userType=User.UserType; // this brings your UserType from database
// then you can use this as
TempData["UserType"]=userType;
希望这有助于你!