c# - ActionFilterAttribute 如何访问受保护的 int?来自基本控制器?
问题描述
我有一个基本控制器,其唯一目的是从中获取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);
}
}
我已阅读此问题和答案,但无法弄清楚该解决方案如何适用于我的情况。
有什么建议么?
解决方案
您不能直接访问类的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"
}));
}
}
推荐阅读
- python - 在 python 3 中使用正则表达式查找子字符串的最佳方法
- android - androidx: SwitchPreference VS SwitchPreferenceCompat
- javascript - 无法在 Spring MVC 4.3.9 中更改表单标记(方法获取)中的操作(参数)属性
- c# - NLog 似乎忽略了 .NET Core 3.1 Windows 服务中的配置文件位置
- python - Python 使用列表搜索列表,所有和任何
- sql - 从表中删除一个项目(行),但保留未使用的 ID 号以供将来插入
- java - OAuth 1.0“无法对您进行身份验证。”
- linux - 如何使用 linux 将列名更改为小写并按原样存储文件?
- python - 围绕预测线图绘制置信区间
- aws-lambda - HIVE_CANNOT_OPEN_SPLIT:打开 Hive 拆分 s3://***/date=2020-05-28/hour=20/part-00000-.c000.snappy.parquet 时出错(偏移量=0,长度=22009):