【问题标题】:How to pass the current user from the Api layer to service layer如何将当前用户从 Api 层传递到服务层
【发布时间】:2016-03-25 16:15:28
【问题描述】:

在 WebApi 中,我可以通过这种方式使用 AspIdentity 获取当前用户

User.Identity.GetUserId<long>();

但是,服务层不知道 AspIdentity。而且我不想将当前用户作为所有方法的参数传递。

换句话说,我可以使用什么模式将当前用户带到我想要的任何地方。

这样做的原因是记录当前用户在应用程序中所做的所有活动。

【问题讨论】:

  • 它不需要知道AspIdentity。您可以将从User 检索到的IPrincipal 向上传递到较低层。否则,唯一剩下的就是使用静态 HttpContext,这将是一种反模式。
  • @Nkosi 没有通用的方法吗?喜欢使用这个 System.Security.Claims.ClaimsPrincipal.Current?我正在研究的相关问题stackoverflow.com/questions/53092899/…

标签: asp.net-mvc asp.net-web-api2 asp.net-identity n-tier-architecture


【解决方案1】:

API 旨在无状态,您可以使用当前登录的用户,但您可能有第三方应用程序访问您的 API。因为它是无状态的,所以当前用户的处理方式与标准 Web 调用不同。

长话短说:无论您要对 API 用户进行身份验证,都需要将用户名/用户 ID 向下传递到服务层。好消息是,一旦您进行了此设置,您就可以对 API 和非 API 调用使用相同的服务层方法。

【讨论】:

    【解决方案2】:

    最后我是这样实现的。

    在框架层(一个独立于社区的项目)中,我添加了这个:

    public interface ICurrentContextProvider<T>
    {
        T GetCurrentUser();      
    }
    

    在 API 中我添加了这个接口的实现,类似于:

    public  ApplicationUser GetCurrentUser()
    {
         return _usersService.FindByIdAsync(Convert.ToInt64(HttpContext.Current.User.Identity.GetUserId())).Result;
    }
    

    而且由于所有其他层都知道框架层,我可以在任何地方调用它,而无需引用 AspIdentity,也无需将当前用户传递给我的所有函数。

    注意:我将其设为通用是因为以下原因: 1-框架(公共层)不了解应用程序用户 2-我可以从上下文中获取任何其他类型,例如很长的 ApplicationUserId。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 2012-09-19
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多