如何从UserProfile获取自定义信息

本文关键字:自定义 信息 获取 UserProfile | 更新日期: 2023-09-27 18:26:16

我在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][AllowAnonyment][ValidateAntiForgeryToken]public ActionResult登录(LoginModel模型,字符串returnUrl){if(ModelState.IsValid&&WebSecurity.Login(model.UserName,model.Password,persistCookie:model.ErememberMe)){var context=new UsersContext();var user=上下文。UserProfiles.Where(u=>u.UserName==model.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); 
}`

如何从UserProfile获取自定义信息

这只是一个想法,以防我无法评论我的声誉,为什么不直接使用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;

希望这对你有帮助!