IHttpContextAccessor在类中为null

时间:2018-02-28 14:39:11

标签: c# asp.net asp.net-core-2.0 httpcontext

当我试图从IHttpContextAccessor字段获取httpcontext时,我遇到了问题。

有我的startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddDistributedMemoryCache();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<IUserContextServices, UserContextService>();
    services.AddSession(options =>
    {
        options.Cookie.Name = ".AdventureWorks.Session";
        options.IdleTimeout = TimeSpan.FromSeconds(10);
    });
}

这是实现IUserContext接口的My UserContext类

public class UserContextService : IUserContextServices
{
    private readonly IHttpContextAccessor contextAccessor;
    PQADBContext _context = new PQADBContext();

    public UserContextService(IHttpContextAccessor accessor)
    {
        contextAccessor = accessor;
    }

   public UserContextService()
    {

    }

    public HttpContext Context
    {
        get
        {
            return contextAccessor.HttpContext;
        }
    }
   public int UserID()
    {
       return Context.Session.GetID("UserID").ConvertToInt();
    }
    public bool isLogin()
    {
        return Context.Session.GetBoolean("isLogin").ConvertToBool();
    }
      public UserAccount CreateSession(LoginViewModel logindata, bool EncryptPwd = true)
    {
        string error;
        error = "";
        try
        {
            string EncPwd = EncryptPwd ? EncryptDecryptHelper.Encrypt(logindata.Password) : logindata.Password;
            var UserDetail =_context.UserAccount.Where(e => e.P_No == logindata.PNo && e.Password == EncPwd).SingleOrDefault();


            if (UserDetail != null)
            {

                //HttpContext.Session.SetInt32()

                // ///put all the properties in session variables
                 Context.Session.SetBoolean("isLogin", true);
                Context.Session.SetID("UserID",UserDetail.AccountId);
                Context.Session.SetID("P_No",Convert.ToInt32(UserDetail.P_No));
                Context.Session.SetBoolean("isActive", true);
                Context.Session.SetBoolean("Email", true);
                Context.Session.SetID("RoleId", 1);
                Context.Session.SetString("userName", "admin"); 
   }

httpContext在上面的类中可用并且还设置了Session值,但是当我尝试访问此类中的httpcontext时它给了我null对象引用

public class UserService
{
   private readonly IHttpContextAccessor contextAccessor;
    public IUserContextServices _userContext = new UserContextService();
   public UserService()
    {  
    }
 public bool CreateEmployee(AppEmployees appemployee, int RoleId, bool isEmailSend, out string error)
    {
appemployee.CreatedBy = _userContext.UserID(); //this line shows null reference exception
        appemployee.CreatedDate = DateTime.Now;
}

3 个答案:

答案 0 :(得分:3)

您正在使用无参数构造函数

新建UserContextService
public IUserContextServices _userContext = new UserContextService();

而不是依赖依赖注入。

您需要配置要与DI容器一起使用的UserService - 通过构造函数注入

public class UserService
{
    private readonly IUserServiceContext _userServiceContext;

    public UserService(IUserServiceContext userServiceContext)
    {
        _userServiceContext = userServiceContext;
    }
}

您还需要修改Startup.cs以注册UserService,您可能还希望它实现一个接口

答案 1 :(得分:1)

为什么在UserService中使用默认构造函数?

您使用下一个代码:

public IUserContextServices _userContext = new UserContextService();

当然,IHttpContextAccessor为空。

您需要在UserService中使用DI。

示例:

private readonly IUserContextService _userContextService;
public UserService(IUserContextService userContextService)
{  
    _userContextService = userContextService;
}

.NET Core中有关于DI的好post

答案 2 :(得分:0)

如果你直接将UserId设置为

public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
    UserId = httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
}

这样你在大多数情况下可能会得到 null UserId 而不是先创建 httpContextAccessor 字段

public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
     this.httpContextAccessor = httpContextAccessor;
}
public string UserId { get { return httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); } }

然后获取UserId,这样就解决了获取空UserId的问题。