繁体   English   中英

无法获取分配给HttpContext.User的变量

[英]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是必经之路。

分配用户可以,但是分配不会在请求之间持久。 您必须确保在每个请求的开始时设置用户,也许是在自定义AuthorizeAttributeIHttpModule 例如,您可能具有如下逻辑:

  • 从请求中检索相关的cookie
  • 验证cookie是否对应于有效的会话(例如,通过查询包含此信息的数据库)
  • 根据cookie检索会话信息并将其存储在User属性中

此外,当您分配HttpContext.Current.User时,请考虑同时分配Thread.CurrentPrincipal

在ASP.NET MVC应用程序中读取传递数据

您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM