获取当前用户,检索信息并在Cookie中存储

时间:2016-10-05 19:23:33

标签: c# asp.net-mvc-5 asp.net-identity-2

我已将ApplicationUser扩展为包含有关用户的其他一些信息:

public class ApplicationUser : IdentityUser
{
    public string AmptechEmployeeID { get; set; }
    public EnumIdentityNavigationType NavigationType { get; set; }
    public EnumPanelBarExpandMode PanelBarExpandMode { get; set; }
    public EnumIdentityTheme Theme { get; set; }
    public EnumIdentityBreadcrumbs Breadcrumbs { get; set; }
    public EnumIdentityHeaderFooter Header { get; set; }
    public EnumIdentityHeaderFooter Footer { get; set; }

现在,当用户登录应用程序时,我想检索信息并将其存储在cookie中:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:
            Response.AppendCookie(GetUserInfo());
            return RedirectToLocal(returnUrl);
        case SignInStatus.LockedOut:
            return View("Lockout");
        case SignInStatus.RequiresVerification:
            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
        case SignInStatus.Failure:
        default:
            ModelState.AddModelError("", "Invalid login attempt, the User Name and/or Password you supplied is/are invalid");
            return View(model);
    }
}

public HttpCookie GetUserInfo()
{
    var db = new ApplicationDbContext();
    var userid = User.Identity.GetUserId();
    ApplicationUser CurUser = db.Users.Find(userid);

    HttpCookie cookie = new HttpCookie("UserInfo");
    cookie["UserName"] = CurUser.UserName;
    cookie["AmptechEmployeeID"] = CurUser.AmptechEmployeeID;
    cookie["Breadcrumbs"] = CurUser.Breadcrumbs;
    cookie["Footer"] = CurUser.Footer;
    cookie["Header"] = CurUser.Header;
    cookie["NavigationType"] = CurUser.NavigationType;
    cookie["PanelBarExpandMode"] = CurUser.PanelBarExpandMode;
    cookie["Theme"] = CurUser.Theme;

    return cookie;
}

当我运行应用程序时,我收到以下错误:

enter image description here

我在这里做错了什么?

0 个答案:

没有答案