【问题标题】:asp.net mvc - need to store some data for the current requestasp.net mvc - 需要为当前请求存储一些数据
【发布时间】:2015-11-29 18:06:50
【问题描述】:

我正在编写一个用户认证类。在请求期间有很多对当前用户的引用,所以我想将它缓存在内存中,而不是调用数据库ala singleton。我正在考虑使用会话并在每个请求结束时清除它。

喜欢:

 public static User Current() {
     if (Session["current-user"] == null) {
          Session["current-user"] = GetUserFromDB(); // example function, not real
     }
     return (User)Session["current-user"];

然后在 app_end 请求中:

     Session.Clear();

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:
    HttpContext.Items["user"] = user;
    

    你可以在整个请求过程中引用上下文项,它会在请求结束时被清除。

    【讨论】:

    • 在视图中这是 ViewContext.HttpContext.Items
    【解决方案2】:

    使用HttpContext 类。您可以在 HttpContext.Current 的控制器的上下文中访问它。

    HttpContext.Items 集合是您想要使用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2021-06-30
      相关资源
      最近更新 更多