当我尝试从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时,它为我提供了空对象引用

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;
}

最佳答案

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

您使用下一个代码:

public IUserContextServices _userContext = new UserContextService();


当然,这里IHttpContextAccessor为空。

您需要在UserService中使用DI。

例:

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


.NET Core中有关DI的很好的post

关于c# - IHttpContextAccessor在类中为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49032091/

10-13 08:02