【问题标题】:How can acces ClaimsIdentity on Logic Layer如何访问逻辑层上的 ClaimsIdentity
【发布时间】:2021-04-08 02:58:10
【问题描述】:

我想将此服务转移到逻辑上以便在任何地方使用,但我无法成功,因为它来自控制器。

我有两个服务。有读取缓存,我在验证时在控制器层使用它们。

我的第一个逻辑是读取缓存中的 companyId

     public virtual int GetCompanyIdFromCache(int id)
    {
        _memCache.TryGetValue(id, out int companyId);
        return companyId;
    }

我的第二个服务也在控制器上。 (帮助我找到用户的 id)

[HttpGet]
    [Route("GetCompanyId")]
    public int GetCompanyPublicId()
    {
        if (User.Identity is ClaimsIdentity claimsIdentity)
        {
            var userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
            var companyId = _userService.GetCompanyIdFromCache(Convert.ToInt32(userId));
            return companyId;
        }

        throw new ArgumentException("Can't be found Company");
    }

我想在任何地方都使用这种方法,所以我想将第二个服务完全移动到逻辑层,但用户字段来自 ControllerBase(我猜是在 HttpContext 上),我无法将它移动到逻辑层

if (User.Identity is ClaimsIdentity claimsIdentity)

我应该如何重构逻辑层?

【问题讨论】:

    标签: c# asp.net .net asp.net-core asp.net-web-api


    【解决方案1】:

    据我所知,User.Identity 是 ClaimsIdentity,它是控制器库中的一个属性。我们不能直接在其他方法中使用它。

    如果你想通过其他服务方式访问User.Identity,我建议你可以尝试注入httpaccessor服务并从中获取ClaimsIdentity。

    更多细节,您可以参考以下代码:

    创建我的类:

    public class Myclass
    {
        public IHttpContextAccessor _accessor { get; set; }
         public Myclass(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
    
          var re =  accessor.HttpContext.User.Identity as ClaimsIdentity;
            int i = 0;
        }
    
        public string GetName() {
            var re = _accessor.HttpContext.User.Identity as ClaimsIdentity;
    
            string name = re.Claims.First(x => x.Type == "name").Value;
    
            return name;
        }
    }
    

    Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();
            services.AddHttpContextAccessor();
            services.AddScoped(typeof(Myclass));
        }
    

    用法:

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        public Myclass test { get; set; }
    
        public HomeController(ILogger<HomeController> logger, Myclass _test)
        {
            _logger = logger;
            test = _test;
        }
    
        public async Task<IActionResult> IndexAsync()
        {
            var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            claimsIdentity.AddClaim(new Claim("name", "aaaa"));
            await HttpContext.SignInAsync(
               CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity)
            );
            return View();
        }
    
        public async Task<IActionResult> PrivacyAsync()
        {
            var  re= test.GetName();
    
            return View();
        }
    
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 2012-08-30
      • 2012-07-06
      • 2012-11-26
      • 2010-10-02
      • 1970-01-01
      • 2021-01-04
      • 2014-09-07
      • 1970-01-01
      相关资源
      最近更新 更多