我有一个基本控制器,其唯一目的是从int
获取一个HttpContext.Session
值并将其提供给所有继承的控制器。
现在,当未设置该值并且用户尝试不登录而访问受限视图时,我正尝试重定向到登录视图。
这是到目前为止我得到的:
public class BaseController : Controller
{
protected int? BranchId
{
get { return (HttpContext.Session.GetInt32("BranchId") as int?); }
set {}
}
public BaseController() {}
}
public class RedirectingActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (BranchId < 1) // BUT BranchId DOES NOT EXIST IN THIS CONTEXT
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Home",
action = "Login"
}));
}
}
}
public class EmployeesController : BaseController
{
private readonly VaktlisteContext db;
private readonly IMapper auto;
public EmployeesController(VaktlisteContext context, IMapper mapper)
{
db = context;
auto = mapper;
}
[RedirectingAction]
public async Task<IActionResult> Index()
{
Branch branch = await db.Branches.Include(e => e.Employees)
.Where(b => b.Id == BranchId).FirstOrDefaultAsync();
if (branch == null) return NotFound();
BranchViewModel vm = auto.Map<BranchViewModel>(branch);
return View(vm);
}
}
我已经读过this question and answer,但是无法弄清楚该解决方案如何适用于我的情况。
有什么建议吗?
答案 0 :(得分:1)
您不能直接访问BranchId
类的RedirectingActionAttribute
属性,因为它是BaseController
类的成员。
尝试以下代码:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if ((filterContext.Controller as BaseController).BranchId < 1)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Home",
action = "Login"
}));
}
}
答案 1 :(得分:1)
受保护的道具是受保护的,当您将一个属性定义为受保护的访问权限时,就不能期望在派生类中访问它!!
但是要访问实际的财产
public class ValidateActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.Controller as BaseController ;
if (controller == null)
{
throw new InvalidOperationException("It is not EmployeesController!");
}
var propVal= controller.PropertyName;
//check propVal here
}
}
但是您也可以像Session
中的context.HttpContext.Session
一样使用ActionFilter