Accessing logged in user Id from class - MVC 5, Au

2019-07-23 06:36发布

问题:

So In my project have implemented interfaces and AutoMapper, and Identity 2.0 with Id as int modification form here: http://typecastexception.com/post/2014/07/13/ASPNET-Identity-20-Extending-Identity-Models-and-Using-Integer-Keys-Instead-of-Strings.aspx

Question is how to access ApplicationUserManager properties from:

public class EnteredByResolver : ValueResolver<ExcursionVM, int>
    {
        protected override int ResolveCore(ExcursionVM source)
        {
            return 1; // TODO - need to access loged user Id to map it to model and save
        }
    }

In my controller it is easy:

public class ManageController : Controller
{
    private ISchedule _ifc;

    public ManageController(ISchedule ifc)
    {
        this._ifc = ifc;
    }

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
    ...

I could access it form interface implementation, but the same (or similar) problem.

Ideas?

回答1:

Instead of using ClaimsPricipal.Current I recommend to use System.Web.HttpContext.Current.User - much more reliable when used in web-application. Or when executed in a controller it'll be HttpContext.User.

However this will not work if this is executed outwith Http request, which is logical: no request - no logged-in user.

ClaimsPrincpial.Current returns Thread.CurrentPrincipal which is not always what you need, since the thread can be IIS thread and you'll get Windows user running IIS. And that is less than ideal.

Also when there is no user logged in and you try to run ClaimsPrincipal.Current.IsInRole("admin"), you will get an exception about "broken trust between domains" (don't remember exact wording).



回答2:

I think you can use

ClaimsPrincipal.Current.Identity.GetUserId();

From memory.

GetUserId() is an extension method in the Identity 2.0 library I beleive, so you need using Microsoft.AspNet.Identity; in the file

See this question and its answers for more details