I add in my UserProfile the custom field UserType as string. I want to change my login post method to get the value from UserType
and pass this value in a TempData.
This is my code on 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);
}
I do a debug on this method, this is the informations that i have:
> **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.
Anybody have some solution for this? I'm new on ASP.NET, but maybe if I implements custom membership it will work, what do you think? Could you send me some example? Thank you guys.
Solution here:
`[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);
}`