Accessing logged in user Id from class - MVC 5, AutoMapper and Identity 2.0

心已入冬 提交于 2019-12-14 02:34:03

问题


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



来源:https://stackoverflow.com/questions/26732822/accessing-logged-in-user-id-from-class-mvc-5-automapper-and-identity-2-0

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