访问登录的用户ID从类 - MVC 5,AutoMapper和标识2.0 [英] Accessing logged in user Id from class - MVC 5, AutoMapper and Identity 2.0

查看:180
本文介绍了访问登录的用户ID从类 - MVC 5,AutoMapper和标识2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,在我的项目已经实施了接口和AutoMapper和Identity 2.0编号如下修改INT形式:<一href=\"http://typecastexception.com/post/2014/07/13/ASPNET-Identity-20-Extending-Identity-Models-and-Using-Integer-Keys-Instead-of-Strings.aspx\" rel=\"nofollow\">http://typecastexception.com/post/2014/07/13/ASPNET-Identity-20-Extending-Identity-Models-and-Using-Integer-Keys-Instead-of-Strings.aspx

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

问题是如何从访问ApplicationUserManager属性:

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
        }
    }

在我的控制器很容易:

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.

想法?

推荐答案

而不是使用 ClaimsPricipal.Current 我推荐使用的System.Web。 HttpContext.Current.User - 在网络的应用程序使用时,更可靠。或者当一个控制器执行这将是 HttpContext.User中

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.

然而,如果这是outwith Http请求,这是合乎逻辑的执行,这将不起作用:无请求 - 不登录用户。

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

ClaimsPrincpial.Current 收益 Thread.CurrentPrincipal中 这并不总是你所需要的,因为线程可以IIS线程,你会得到Windows用户运行IIS。和小于理想

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.

此外,当没有用户登录并尝试运行 ClaimsPrincipal.Current.IsInRole(管理员),您将获得有关之间破坏的信任异常域(不记得确切的字眼)。

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).

这篇关于访问登录的用户ID从类 - MVC 5,AutoMapper和标识2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆