11

尽管我已经在这里待了一段时间,但这是我关于 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 );

这对我来说效率非常低,尽管它只是为丢失的东西创建空对象。

它工作正常。

所以我想我想知道这是否真的可以,我应该停止对性能和效率如此敏感,或者我的恐惧是否正确,在这种情况下我应该做什么?[请不要说“获得生命,伙计!”]

4

2 回答 2

6

不 - 从性能的角度来看,这段代码没有什么特别的错误。在 ASP.NET 的后端创建了大量对象,您的单个对象只是杯水车薪。由于类实例化非常快,我不会担心它。

你为什么在这里忽略会话?会话信息没有过期日期,因此在后台没有额外的检查。除非您使用的是进程外会话服务器,否则您的对象没有序列化(也没有缓存)。缓存适用于每个用户 - 因此您有机会(尽管很小)代码错误返回错误的主体,其中每个用户都有缓存 - 不会冒这种风险。

如果您希望它可用于那里的所有请求(不仅仅是基于 MVC),我会考虑在 Application_PostAuthenticateRequest 中设置它

于 2011-11-25T03:16:28.500 回答
2

这个帖子可能有用。请注意身份验证票证中用户数据的使用。

ASP.NET MVC - 设置自定义 IIdentity 或 IPrincipal

于 2011-11-25T03:23:34.767 回答