ActionFilterAttribute如何访问受保护的int?从BaseController?

时间:2018-12-29 14:23:59

标签: c# asp.net-core-mvc

我有一个基本控制器,其唯一目的是从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,但是无法弄清楚该解决方案如何适用于我的情况。

有什么建议吗?

2 个答案:

答案 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