我想实现一个场景,在这个场景中,目前在我的项目的每个方法中,我正在访问我从claims获得的userId。
因此,我不想在每个方法中都传递claim.UserId,而是希望以这样的方式实现一个解决方案,即声明可以在服务DI中初始化,并且不需要传递每个方法,因此每当服务初始化时,声明也可以同时初始化。例如,用于
Service
{
// something at here
method1{
}
method2{
}
}请向我推荐任何文档或文章或最好的方法。
发布于 2021-07-14 18:54:31
你可以使用IHttpContextAccessor来实现它。
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。
services.AddHttpContextAccessor();https://stackoverflow.com/questions/68376207
复制相似问题