简体   繁体   中英

Get UserId from custom User Identity class

I am trying to access the UserId property from a custom UserIdentity class that I created, but I am having trouble with the syntax to access it.

Here is the class:

using System.Security.Principal;
using System.Web.Security;

namespace Rework.Models
{
    public class UserIdentity : IIdentity, IPrincipal
    {
        private readonly FormsAuthenticationTicket _ticket;

        public UserIdentity(FormsAuthenticationTicket ticket)
        {
            _ticket = ticket;
        }

        public string AuthenticationType
        {
            get { return "User"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }
        }

        public string Name
        {
            get { return _ticket.Name; }
        }

        public string UserId
        {
            get { return _ticket.UserData; }
        }

        public bool IsInRole(string role)
        {
            return Roles.IsUserInRole(role);
        }

        public IIdentity Identity
        {
            get { return this; }
        }
    }
}

Here is the code block in which I try to access the UserId property and put its value into the id variable.

    using (UsersContext db = new UsersContext())
                {

                    if (db.Users.Any(u => u.UserName != txtUsername.Text))
                    {
                        var newUserObj = new User { UserName = txtUsername.Text };
                        UsersContext newUser = new UsersContext();
                        newUser.AddUser(newUserObj);
                    }
                    if (!User.IsInRole("Member") || !User.IsInRole("Admin") || !User.IsInRole("SuperAdmin"))
                    {
                        var id = //This is where I need to access the prop
                        db.AddUserRole(new UserRole {UserId = id, RoleId = 3});
                    }
                }

With the build in class you could do Users.Identity.GetId();, but I'm not too sure how with the custom class. Any help would be appreciated!

I think following code is wrong:

if (db.Users.Any(u => u.UserName != txtUsername.Text))
{
    var newUserObj = new User { UserName = txtUsername.Text };
    UsersContext newUser = new UsersContext();
    newUser.AddUser(newUserObj);
}

The part db.Users.Any(u => u.UserName != txtUsername.Text) bugs me a little. Basicly, you are checking if any user already inside db hasn't got the same username as entered. And if you get some results, you create a new user. That would be practicaly always, since there always will exist a user with different username than entered (except when there are no users). Maybe I'm just misreading this condition, but its still a little confusing to me. ;)

You should rewrite it as:

var user = db.Users.SingleOrDefault(u => u.UserName == txtUsername.Text);
if (user == null)
{
    var user = new User { UserName = txtUsername.Text };
    //UsersContext newUser = new UsersContext(); // Not sure why you need new context, since you are already inside UsersContent
    db.AddUser(user);
    db.SaveChanges(); // only neccessary if User's Id is identity to get newly created Id.
}

After that you can access user.UserId or user.Id property to get Id of a user (current or new)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM