IHttpContextAccessor.HttpContext.User.Identity shows all null properties in CurrentUserService service

前端 未结 1 1375
挽巷
挽巷 2021-01-14 05:08

I am trying to use Jason Taylor\'s Clean Architecture Template, this template uses NSwag to automatically create a TypeScript Client (Angular), but I don\'t need to create a

相关标签:
1条回答
  • 2021-01-14 06:01

    LinkedListT's link in the comments got me in the right direction.

    The link points to an answer which explains this:

    under the ASP.NET MVC framework, the HttpContext (and therefore HttpContext.Session) is not set when the controller class is contructed as you might expect, but it set ("injected") later by the ControllerBuilder class.

    The CurrentUserService class that comes with the template I'm using tries to read the user claims in the constructor, so I moved the code to the property's getter, which executes until latter when the property is actually used, by then all claims and properties are well populated.

    My new CurrentUserService looks like this:

    using CleanREC0.Application.Common.Interfaces;
    using Microsoft.AspNetCore.Http;
    using System.Security.Claims;
    
    namespace CleanREC0.WebUI.Services
    {
        public class CurrentUserService : ICurrentUserService
        {
            private IHttpContextAccessor _httpContextAccessor;
    
            public CurrentUserService(IHttpContextAccessor httpContextAccessor)
            {
                _httpContextAccessor = httpContextAccessor;
            }
    
            public string UserId { get { return _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); }}
        }
    }
    
    0 讨论(0)
提交回复
热议问题