首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我们可以在构造函数中传递ClaimIndentity吗

我们可以在构造函数中传递ClaimIndentity吗
EN

Stack Overflow用户
提问于 2021-07-14 18:16:51
回答 1查看 22关注 0票数 0

我想实现一个场景,在这个场景中,目前在我的项目的每个方法中,我正在访问我从claims获得的userId。

因此,我不想在每个方法中都传递claim.UserId,而是希望以这样的方式实现一个解决方案,即声明可以在服务DI中初始化,并且不需要传递每个方法,因此每当服务初始化时,声明也可以同时初始化。例如,用于

代码语言:javascript
复制
Service
{
  // something at here

method1{


}

method2{

}
}

请向我推荐任何文档或文章或最好的方法。

EN

回答 1

Stack Overflow用户

发布于 2021-07-14 18:54:31

你可以使用IHttpContextAccessor来实现它。

代码语言:javascript
复制
    public class ServiceWithUserId
    {
        private readonly Guid userId;
        private const string nameIdentifierType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";

        public ServiceWithUserId(IHttpContextAccessor httpContextAccessor)
        {

            userId = Guid.Parse(httpContextAccessor.HttpContext.User.Identities.Single().Claims.Single(c => c.Type == nameIdentifierType).Value);
        }

        public void Method1()
        {
            if (userId == Guid.Empty)
            {
                // ...
            }

        }
    }

您还必须在ServiceCollection中添加IHttpContextAccessor。

代码语言:javascript
复制
services.AddHttpContextAccessor();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68376207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档