提问人:Pedro Henrique 提问时间:10/13/2014 最后编辑:Pedro Henrique 更新时间:10/14/2014 访问量:629
如何从UserProfile中获取自定义信息?
How to get custom information from UserProfile?
问:
我在我的 UserProfile 中添加了自定义字段 UserType 作为字符串。我想更改我的并在 TempData 中传递此值。login post method to get the value from UserType
这是我在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] [允许匿名] [验证AntiForgeryToken] public ActionResult Login(LoginModel 模型,字符串 returnUrl) { if (ModelState.IsValid && WebSecurity.Login(model.用户名、模型。密码,persistCookie:模型。记住我)) { var 上下文 = new UsersContext(); var user = 上下文。UserProfiles.Where(u => u.UserName == 模型。用户名); var userType = 用户。选择(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);
}`
答:
只是一个想法,以防万一我因为我的声誉而无法发表评论,
为什么不直接使用而不是使用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;
希望这对您有所帮助!
评论