2013-02-13 137 views
2

我使用ASP.NET MVC4解决方案。当用户登录时,我想显示他的全名(不是登录表单中提供的用户名)。他的全名(名字+姓氏实际存储在我数据库中的用户表中)应显示在右上角。显示登录用户的全名(名字,姓氏)

为了更好的性能,我不希望每个请求完成的时间来查询数据库。

如何继续?

  • 将用户信息(名字,姓氏,...)保存在cookie中?
  • 保持用户信息是应用程序所有生命周期的会话变量?
  • 将用户信息保存在“配置文件”中,如下所述:How to assign Profile values?(*)
  • 还有其他的东西吗?

(*)我认为这个解决方案对于我的使用有点复杂。

谢谢。

回答

1

我会用一个cookie。它不占用你的机器上的任何内存,像会话,它不会像配置文件那样击中数据库。只记得在用户注销时删除cookie。

注意,档案会在您每次请求时访问数据库服务器。据我所知,配置文件数据没有缓存在Web服务器上的任何地方(除非你有一个自定义配置文件提供程序)。

我喜欢cookie的另一个原因是:如果您想要存储任何其他用户信息以便快速访问,例如UserPrimaryKey或任何特殊用户首选项,则可以将它们作为JSON存储在cookie中。下面是一个例子:

另注:下面的代码使用Newtonsoft.Json(所述JsonConvert线)。它应该在MVC4项目中出现,但对于MVC3项目,您可以通过nuget添加它。

public class UserCacheModel 
{ 
    public string FullName { get; set; } 
    public string Preference1 { get; set; } 
    public int Preference2 { get; set; } 
    public bool PreferenceN { get; set; } 
} 

public static class UserCacheExtensions 
{ 
    private const string CookieName = "UserCache"; 

    // put the info in a cookie 
    public static void UserCache(this HttpResponseBase response, UserCacheModel info) 
    { 
     // serialize model to json 
     var json = JsonConvert.SerializeObject(info); 

     // create a cookie 
     var cookie = new HttpCookie(CookieName, json) 
     { 
      // I **think** if you omit this property, it will tell the browser 
      // to delete the cookie when the user closes the browser window 
      Expires = DateTime.UtcNow.AddDays(60), 
     }; 

     // write the cookie 
     response.SetCookie(cookie); 
    } 

    // get the info from cookie 
    public static UserCacheModel UserCache(this HttpRequestBase request) 
    { 
     // default user cache is empty 
     var json = "{}"; 

     // try to get user cache json from cookie 
     var cookie = request.Cookies.Get(CookieName); 
     if (cookie != null) 
      json = cookie.Value ?? json; 

     // deserialize & return the user cache info from json 
     var userCache = JsonConvert.DeserializeObject<UserCacheModel>(json); 
     return userCache; 
    } 

} 

有了这个,你可以读/写从控制器像这样的cookie信息:

// set the info 
public ActionResult MyAction() 
{ 
    var fullName = MethodToGetFullName(); 
    var userCache = new UserCache { FullName = fullName }; 
    Response.UserCache(userCache); 
    return Redirect... // you must redirect to set the cookie 
} 

// get the info 
public ActionResult MyOtherAction() 
{ 
    var userCache = Request.UserCache(); 
    ViewBag.FullName = userCache.FullName; 
    return View(); 
} 
+0

感谢您的答复。问题:我可以在一个cookie中放入多少数据?我的意思是,我必须创建一个逗号分隔值来存储名字;我的cookie中的姓氏?最后一个问题:如果用户离开网站而未注销,该怎么办? Cookie仍然存在...无论如何感谢。 – Bronzato 2013-02-13 11:55:04

+0

我用代码演示了如何使用JSON将附加值存储在cookie中的代码。至于用户离开网站时是否存在cookie,您可以更改Expires属性以告知浏览器在用户关闭浏览器时删除cookie。只是不要在cookie中存储任何敏感信息,如信用卡号码或类似的东西! – danludwig 2013-02-13 12:04:41

+0

谢谢亲爱的。我会尽快尝试,并将回复标记为已接受。 – Bronzato 2013-02-13 12:07:22

相关问题