我从事 ASP.NET MVC4 解决方案。当用户登录时,我想显示他的全名(不是登录表单中提供的用户名)。他的全名(名字+姓实际存储在我数据库的用户表中)应该显示在右上角。
为了获得更好的性能,我不想在每次请求完成时都查询数据库。
如何进行?
- 将用户信息(名字、姓氏……)保存在 cookie 中?
- 保留用户信息是应用程序整个生命周期的会话变量吗?
- 将用户信息保存在“配置文件”中,如下所述:如何分配配置文件值?(*)
- 还有什么?
(*) 我认为这个解决方案对于我的使用来说有点复杂。
谢谢。
我从事 ASP.NET MVC4 解决方案。当用户登录时,我想显示他的全名(不是登录表单中提供的用户名)。他的全名(名字+姓实际存储在我数据库的用户表中)应该显示在右上角。
为了获得更好的性能,我不想在每次请求完成时都查询数据库。
如何进行?
(*) 我认为这个解决方案对于我的使用来说有点复杂。
谢谢。
我会用饼干。它不会像 Session 那样占用您机器上的任何内存,也不会像 Profile 那样访问数据库。只要记住在用户注销时删除 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();
}