我试图通过在我的 Controller 中运行以下代码来从我的身份验证票中获取一些自定义字段值 -

[HttpPost]
    public ActionResult Add(AddCustomerModel customer)
    {
        customer.DateCreated = DateTime.Now;
        customer.CreatedBy = ((CustomPrincipal)(HttpContext.User)).Id;
        customer.LastUpdated = DateTime.Now;
        customer.LastUpdateBy = ((CustomPrincipal)(HttpContext.User)).Id;

        if (ModelState.IsValid)
        {
            _customerService.AddCustomer(customer);

            return RedirectToAction("Index");
        }

        return View(customer);
    }

当我尝试为新客户设置 CreatedBy 字段时,出现以下错误 -



我在 FormsAuthenticationTicket 中的 userData 字段设置了一个 JSON 字符串,其中包含两个字段 - Id 和 FullName。

这是我在 Controller 上的登录方法 -
    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (Membership.ValidateUser(model.EmailAddress, model.Password))
        {
            LoginModel user = _userService.GetUserByEmail(model.EmailAddress);

            CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
            serializeModel.Id = user.ID;
            serializeModel.FullName = user.EmailAddress;
            //serializeModel.MergedRights = user.MergedRights;

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            string userData = serializer.Serialize(serializeModel);

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
             1,
             user.EmailAddress,
             DateTime.Now,
             DateTime.Now.AddHours(12),
             false,
             userData);

            string encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            Response.Cookies.Add(faCookie);

            return RedirectToAction("Index", "Dashboard");
        }

        return RedirectToAction("Index");
    }

我哪里出错了?

最佳答案

要从 cookie 中检索用户数据,您可以使用以下代码

FormsIdentity formsIdentity = HttpContext.Current.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = formsIdentity.Ticket;
string userData = ticket.UserData;

关于asp.net-mvc - 无法检索表单例份验证票证上的用户数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27888964/

10-10 11:10