[英]Cannot get variable I assigned to HttpContext.User
我正在使用MVC 4创建一个使用自定义逻辑的基本身份验证系统。 我有一个UserModel
类(继承自IPrincipal
),用于存储需要持久化的数据。 为此,我在控制器中使用以下代码:
if (ModelState.IsValid)
{
if (userModel.IsValidUser())
{
FormsAuthentication.SetAuthCookie(userModel.Username, false);
HttpContext.User = userModel;
// User is now logged in; send them to Index method to load MyeMan data
return RedirectToAction("Index", "Login");
}
}
然后,在索引操作中:
if (IsUserLoggedIn())
{
UserModel userModel = (UserModel) HttpContext.User; // This line throws error
}
我得到的错误是:
无法将类型为“ System.Web.Security.RolePrincipal”的对象转换为类型为“ MyProj.UserModel”。
当我进行调试时, HttpContext.User
毫无疑问地接受了UserModel
。 仅当它重定向到其他操作时,其数据类型才会更改。
我是在做错什么,还是在没有会话的情况下永久存储UserModel
的完全错误的方法? 会话将独立于AuthCookie
过期; 有人告诉我HttpContext.User
是必经之路。
分配用户可以,但是分配不会在请求之间持久。 您必须确保在每个请求的开始时设置用户,也许是在自定义AuthorizeAttribute
或IHttpModule
。 例如,您可能具有如下逻辑:
此外,当您分配HttpContext.Current.User
时,请考虑同时分配Thread.CurrentPrincipal
。
您可以使用TempData
在操作之间传递数据。 它将仅可用于后续请求
TempData["User"] = userModel;
// User is now logged in; send them to Index method to load MyeMan data
return RedirectToAction("Index", "Login");
索引中
UserModel user= (UserModel)TempData["User"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.