Tom*_*nto 7 .net c# asp.net-mvc
我不确定这是否是最好的方法,但我希望在当前用户的所有请求期间保持用户对象的活动状态.通过阅读几个资源,我了解到你应该创建自己的IPrinciple来保存它.但我不希望每个身份验证请求都触发数据库.关于如何处理这个问题的任何建议?缓存db请求是个好主意吗?
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
User user;
using (HgDataContext hg = new HgDataContext())
{
if (Session["user"] != null)
{
user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
} else
{
user = Session["user"] as User;
}
}
var principal = new HgPrincipal(user);
Context.User = principal;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在使用以下代码来缓存用户,请注意在更新后删除缓存!
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
User user;
Cache cache = HttpContext.Current.Cache;
using (HgDataContext hg = new HgDataContext())
{
user = cache[authTicket.Name] as User;
if (user == null)
{
user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
cache[authTicket.Name] = user;
}
}
var principal = new HgPrincipal(user);
Context.User = principal;
}
}
Run Code Online (Sandbox Code Playgroud)