HttpContext null in constructor

旧时模样 提交于 2019-12-11 04:40:16

问题


I have a UserContext Service where I'll put some basic functionalities ("IsAuthenticated, GetUser etc...)

In order to do that, I need to pass the HTTPContext from my WebAPI Controller to my Class Library Service.

Actually, HttpContext is always null in the web api controller.

Anybody have a solution to resolve my issue ?. Is there a better way to acheive it.

Web API User Controller

[Route("api/[controller]")]
[Authorize]
public class UserController : Controller
{
    private readonly IUserContextServices _userContextServices;
    private readonly User loggedUser;

    public UserController()
    {
       //HttpContext ALWAYS NULL
        _userContextServices = new UserContextService(HttpContext);
    }
 }  

UserContext Services

namespace MyProj.Services
{
    public interface IUserContextServices
    {
        UserContext GetUserContext();
        bool IsUserAuthenticated();
    }

    public class UserContextService : IUserContextServices
    {
        private readonly HttpContext _context;
        private UserContext _userContext;
        public UserContextService(HttpContext context)
        {
            _context = context;
            InitUserContext();
        }

        private IEnumerable<Claim> GetUserClaims()
        {
            if (IsUserAuthenticated())
            {
                return _context.User.Claims;
            }
            return null;
        }

        private void InitUserContext()
        {
            if (IsUserAuthenticated())
            {
                var claims = GetUserClaims();
                _userContext = new UserContext();
                _userContext.Email = claims.First(p => p.Type == "email").Value;
                _userContext.AspNetUserID = claims.First(p => p.Type == "sub").Value;
            }
        }

        public UserContext GetUserContext()
        {
            return _userContext;
        }

        public bool IsUserAuthenticated()
        {
            return _context.User != null && _context.User.Identity != null && _context.User.Identity.IsAuthenticated;
        }
    }
}

回答1:


HttpContext is not available when the constructor of the Controller is called. You are going to have to redesign your code to get the context later in the invocation flow. This is what the IHttpContextAccessor is for.

public interface IHttpContextAccessor {
    HttpContext HttpContext { get; }
}

Inject that into the service and then access the context later as needed.

public class UserContextService : IUserContextServices {
    private readonly IHttpContextAccessor contextAccessor;
    private UserContext _userContext;
    public UserContextService(IHttpContextAccessor accessor) {
        contextAccessor = accessor;
    }

    private HttpContext Context {
        get {
            return contextAccessor.HttpContext;
        }
    }

    public UserContext GetUserContext() {
        if (_userContext == null && IsUserAuthenticated()) {
            var claims = Context?.User?.Claims;
            _userContext = new UserContext() {
                Email = claims.First(p => p.Type == "email").Value,
                AspNetUserID = claims.First(p => p.Type == "sub").Value
            };
        }
        return _userContext;
    }

    public bool IsUserAuthenticated() {
        return Context?.User?.Identity?.IsAuthenticated;
    }
}

Inject the service abstraction into the Controller

[Route("api/[controller]")]
[Authorize]
public class UserController : Controller {
    private readonly IUserContextServices _userContextServices;
    private readonly User loggedUser;

    public UserController(IUserContextServices userContextServices) {
        _userContextServices = userContextServices;
    }

    //...
}

IHttpContextAccessor is not in the service collection by default so you need to add it in Startup.ConfigureServices manually in order to be able to inject it:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IUserContextServices, UserContextService>();


来源:https://stackoverflow.com/questions/44683318/httpcontext-null-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!