【发布时间】:2015-01-11 15:48:40
【问题描述】:
我试图通过在我的控制器中运行以下代码从我的身份验证票中获取一些自定义字段值 -
[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 字段时,我收到以下错误 -
无法将“System.Security.Principal.GenericPrincipal”类型的对象转换为“GMS.Core.Models.CustomPrincipal”类型。
FormsAuthenticationTicket 中的我的 userData 字段设置为 JSON 字符串,其中包含两个字段 - Id 和 FullName。
这是我在控制器上的登录方法 -
[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");
}
任何想法我哪里出错了?
【问题讨论】:
-
您在
Global.asax中是否有一个protected void Application_PostAuthenticateRequest(object sender, EventArgs e)方法,您可以在其中创建CustomPrincipal并将其分配给HttpContext.Current.User?
标签: asp.net-mvc asp.net-mvc-4 authentication