我正在尝试通过使用int
使BranchId
变量HttpContext.Session.GetInt32("BranchId").Value
在我的应用程序中可用。
当我根据自己的尝试以及对this question的回答而收集时,这种方法将行不通:
基本控制器类:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Vaktliste.Controllers
{
public class MyBaseControllerClass : Controller
{
public readonly int branchId;
public MyBaseControllerClass()
{
var s = HttpContext.Session; // <-- This causes a NULL exception
// SET THE VARIABLE HERE:
BranchId = s.GetInt32("BranchId") != null
? s.GetInt32("BranchId").Value
: 0;
}
}
}
应用程序中另一个控制器的示例:
namespace Vaktliste.Controllers
{
public class BranchesController : MyBaseControllerClass
{
private readonly VaktlisteContext db;
public BranchesController(VaktlisteContext context)
{
db = context;
}
public async Task<IActionResult> Details(int? id)
{
// USE THE VARIABLE HERE:
if (id == null) id = BranchId;
if (id == null) return NotFound();
var branch = await db.Branches
.Where(m => m.Id == id)
.FirstOrDefaultAsync();
if (branch == null) return NotFound();
HttpContext.Session.SetInt32("BranchId", branch.Id);
return View(branch);
}
}
}
我当然可以在每个控制器中执行GetInt32("BranchId")
,但我想使其保持DRY(不要重复自己)。怎么办?
答案 0 :(得分:1)
也许您可以通过属性来实现。创建basecontroller后,httpcontext.session为null。如果您使用媒体资源并且仅在您的路线中访问它,则该会话应该可用。
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Vaktliste.Controllers
{
public class MyBaseControllerClass : Controller
{
public readonly int branchId;
protected int BranchId {
get { HttpContext.Session?.GetInt32("BranchId")?.Value ?? 0; }
set { HttpContext.Session.SetInt32("BranchId", value); }
}
public MyBaseControllerClass()
{
}
}
}
然后只需访问属性即可获取值
namespace Vaktliste.Controllers
{
public class BranchesController : MyBaseControllerClass
{
private readonly VaktlisteContext db;
public BranchesController(VaktlisteContext context)
{
db = context;
}
public async Task<IActionResult> Details(int? id)
{
// USE THE VARIABLE HERE:
id = id ?? BranchId;
if (id == null) return NotFound();
var branch = await db.Branches
.Where(m => m.Id == id)
.FirstOrDefaultAsync();
if (branch == null) return NotFound();
BranchId = branch.Id;
return View(branch);
}
}
}
答案 1 :(得分:1)
我要制作一个protected
变量,然后用它来包装您的访问器:
protected int? BranchId
{
get { return (HttpContext.Session["BranchId] as int?); }
set { HttpContext.Session.SetInt32("BranchId", value);
}
然后将倒数第二行更新为:
this.BranchId = branch.Id;
当然,所有子类的控制器都只访问受保护的变量。