简体   繁体   中英

Getting identity from another method in the same class

Into class I get logged user like

public static GetUserById_Result GetUser(string userId)
        {
            GetUserById_Result user = new GetUserById_Result();

            try
            {
                using (EF.SSMA oContext = new EF.SSMA())
                {
                    user = oContext.GetUserById(userId).FirstOrDefault();
                }
            }
            catch (Exception)
            {
                throw;
            }

            return user;
        }

So it runs fine. But in the same class I want to acces user value into another method

 public static List<GetUsers_Result> SelectAll()
        {
            List<GetUsers_Result> lstResult = new List<GetUsers_Result>();


            try
            {
                using (EF.SSMA oContext = new EF.SSMA())
                {

                    lstResult = oContext.GetUsers().Where().ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lstResult;
        }

What I need to do to achieve that?, into controller is really simple I just do this:

        var users = User.Identity.GetUserId();

            GetUserById_Result currentUser = UserClass.GetUser(users);
            var role = currentUser.BranchOfficeId;

But how can I acces it in the same class' I try to call GetUserId with

 System.Web.HttpContext.Current.User.Identity.GetUserId(); 

but it just mark HttpContext in red and say "Cannot resolve symbol 'HttpContext'"

My target is to call only users who BranchOfficeId = user.BranchOfficeId

Help is very appreciated. Regards

如果我很好地理解了您的问题,请确保已安装软件包Microsoft.Owin.Host.SystemWebusing System.Web添加,然后直接使用User.Identity.GetUserId()

The reason you can do this in the controller is because Controller has an HttpContext property, which has been created with the details of the current request, including the identity of the current user.

If you want to access the user from another class, you need to pass the user as an argument to your method. As an example:

using System.Security.Principal;

public class SomeClass
{
    public void SomeMethod(IPrincipal user)
    {
        // Whatever you need
    }
}

Then in your controller:

var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User);

However, if you're only interested in the user's name, then you can actually just pass a string instead:

public class SomeClass
{
    public void SomeMethod(string username)
    {
        // Whatever you need
    }
}

Then in your controller:

var someClass = new SomeClass();
someClass.SomeMethod(HttpContext.User.Identity.Name);

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