我試圖通過運行在我的控制器下面的代碼從我的身份驗證票證一些自定義字段值 -無法在窗體身份驗證票證檢索的UserData
[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 Application_PostAuthenticateRequest(object sender,EventArgs e)'方法創建'CustomPrincipal'並將其分配給'HttpContext.Current .User'? –