【发布时间】:2014-03-25 11:01:00
【问题描述】:
我正在使用 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 是要走的路。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 authorization