各位好 最近在練習 net core MVC
不曉得為什麼 controller 的建構子裡想把session裡的值賦予私有變數卻失敗
NullReferenceException: Object reference not set to an instance of an object.
有把app.UseSession(); 放在Startup.cs Configure()裡的最上面也一樣
不曉得原因是甚麼,如何解決? 謝謝。
public class HomeController : Controller
{
//private readonly ILogger<HomeController> _logger;
public AccountRepository Repository { get; }
public loginFunction loginFn {get;}
private int? loginID;
private int? loginAuthority;
private string loginName;
public HomeController(AccountRepository repository)
{
this.Repository = repository;
this.loginFn = new loginFunction();
this.loginID = HttpContext.Session.GetInt32("loginID");
}
}
https://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors
應該是一樣的問題,執行到 this.loginID = HttpContext.Session.GetInt32("loginID");
這行時,HttpContext
物件還沒有被設定。
可以覆載 OnActionExecuting
方法,或注入 IHttpContextAccessor 。
目前是先這樣做 看起來是可以的
只是感覺多繞一圈
public class httpContextClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session=> _httpContextAccessor.HttpContext.Session;
public httpContextClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor=httpContextAccessor;
}
public int? Get(string key)
{
return _session.GetInt32(key);
}
}
public class HomeController : Controller
{
private int? loginID;
private httpContextClass httpContext;
public HomeController(AccountRepository repository, IHttpContextAccessor httpContextAccessor)
{
this.httpContext = new httpContextClass(httpContextAccessor);
this.loginID = this.httpContext.Get("loginID");
}
}
在 Controller 中直接使用 _httpContextAccessor.HttpContext
不就好了,為什麼還要宣告另一個類別?
....你說的對
我原先是參考在controller以外使用session的文章去做的
根據大大提醒後
改寫成直接使用 httpContextAccessor.HttpContext也是可行的
謝謝