尽管我已经在这里待了一段时间,但这是我关于 SO 的第一个问题,所以请对我温柔一点。
我正在使用ASP.NET MVC 3
并且我想创建一个自定义Principal
,因此我可以存储比标准更多的有关当前用户的信息,因此不必经常访问数据库。这是我所追求的相当标准的东西。让我们首先说电子邮件地址和用户 ID。
我决定将对象存储在缓存中,因为我知道不建议将其存储在会话中。
我也不想继续投射User
对象,所以我想覆盖User
控制器中的对象。所以我可以去User.UserId
保证一些事情。
所以我创建了一个这样的自定义主体:
public class MyPrincipal : IPrincipal
{
public MyPrincipal(IIdentity ident, List<string> roles, string email, Guid userId)
{
this._identity = ident;
this._roles = roles;
this._email = email;
this._userId = userId;
}
IIdentity _identity;
public IIdentity Identity
{
get { return _identity; }
}
private List<string> _roles;
public bool IsInRole(string role)
{
return _roles.Contains(role);
}
private string _email;
public string Email
{
get { return _email; }
}
private Guid _userId;
public Guid UserId
{
get { return _userId; }
}
}
我有一个这样的基本控制器:
public class BaseController : Controller
{
protected virtual new MyPrincipal User
{
get
{
if (base.User is MyPrincipal)
{
return base.User as MyPrincipal;
}
else
{
return new MyPrincipal(base.User.Identity, new List<string>(0), "", Guid.Empty );
}
}
}
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if (User != null)
{
if (User.Identity.IsAuthenticated)
{
if (User.Identity is FormsIdentity)
{
FormsIdentity id = base.User.Identity as FormsIdentity;
MyPrincipal principal = (MyPrincipal)filterContext.HttpContext.Cache.Get(id.Name);
if (principal == null)
{
MembershipUser user = Membership.GetUser();
// Create and populate your Principal object with the needed data and Roles.
principal = new MyPrincipal(id, Roles.GetRolesForUser(id.Name).ToList(), user.Email, (Guid)user.ProviderUserKey);
filterContext.HttpContext.Cache.Add(
id.Name,
principal,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
new System.TimeSpan(0, 30, 0),
System.Web.Caching.CacheItemPriority.Default,
null);
}
filterContext.HttpContext.User = principal;
System.Threading.Thread.CurrentPrincipal = principal;
base.OnAuthorization(filterContext);
}
}
}
}
}
如果你看一下,你会很快意识到如果用户没有登录,那么对对象的任何调用User
都必须通过这段代码运行:
return new MyPrincipal(base.User.Identity, new List<string>(0), "", Guid.Empty );
这对我来说效率非常低,尽管它只是为丢失的东西创建空对象。
它工作正常。
所以我想我想知道这是否真的可以,我应该停止对性能和效率如此敏感,或者我的恐惧是否正确,在这种情况下我应该做什么?[请不要说“获得生命,伙计!”]