首页 > 解决方案 > ActionFilterAttribute 如何访问受保护的 int?来自基本控制器?

问题描述

我有一个基本控制器,其唯一目的是从中获取intHttpContext.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);
    }
}

我已阅读此问题和答案,但无法弄清楚该解决方案如何适用于我的情况。

有什么建议么?

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

解决方案


您不能直接访问类的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"
        }));
    }
}

推荐阅读