Best practice to maintain a user id (MVC)

时光毁灭记忆、已成空白 提交于 2019-12-03 14:45:46

I had the same question when I implemented a custom membership provider for MVC. I ended up doing two things. I store the user's Id in the ProviderUserKey field of the MembershipUser object. See provideruserkey. Then to answer your question, yes I created a custom principal from System.Web.Security.IPrincipal, though I later inherited from System.Web.Security.RolePrincipal instead since I wanted support for Roles.

public class MyPrincipal : RolePrincipal
{
    public Guid Id { get; set; }

    public MyPrincipal(string providerName, IIdentity identity, Guid id) : base(identity)
    {
        Id = id;
    }
}

Update: The reason I didn't want to use session in my case is because I've disabled it for the app. I've read that the core concept behind MVC is that separation of concerns, and that is closely models the way the web works, which is stateless. Though I can't remember where I read that now that I try to remember. However I do remember also reading that if you can eliminate the session you should do so. It will allow IIS to serve up simultaneous requests from your app rather than having to wait for one request to finish (and release the user's session) before the next request can use the session and send it's response. The biggest impact of which is loading page content using Ajax.

Are your usernames unique? If so there's no need to maintain the UserId as you can simply retrieve a user by username.

My MVC projects have implemented Membership in much the same was as a traditional Web Forms application. I don't think there is any reason to look at the two differently unless you're trying to build a stateless REST type application. How did you maintain your UserId in Web Forms? Session? Then use session in MVC. There's no reason to reinvent the wheel.

Of course if you have other reasons for changing there are a lot of way to store the UserId. You could store it in the UserData of the authentication cookie. You could also create your own Authentication ticket that uses the UserId as a key rather than the username. You could even create a Custom Principal to store some additional information.

You may want to review Forms Authentication Configuration and Advanced Topics . This article covers storing additional data (UserId) in the authentication ticket and creating a Custom Principal. Both methods would likely fit your requirements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!