在我的网站上,我有一些controller
s仅限于经过身份验证的用户。除此之外,还有一些需要身份验证的控制器,还需要根据一年中的时间进行限制。
为了解决这个问题,我创建了一个TimeRangeFilter
ActionFilter
/ ResourceFilter
。
这是它的样子:
public class TimeRangeFilter : Attribute, IActionFilter, IOrderedFilter
{
public string AllowedMonths { get; set; } // like |3|4|5|
public string RedirectUrl { get; set; }
...... // OnActionExecuting....
}
然后,在我的Controller
的class
上,我实现如下:
[TimeRangeFilter(AllowedMonths = "|3|4|", RedirectUrl = "/feature/welcome", Order = 1)]
[Authorize]
[IsNotNefarious]
public class HubController : BaseController
{...}
但是,即使IOrderedFilter
上的interface
filter
,AuthorizationFilter
首先执行,然后我的TimeRangeFilter
。
对于此欢迎页面,我不希望要求用户登录才能看到它。但我不想根据允许的月份更改到我的Hub页面的URL。
在ActionFilter
执行之前,我如何优先考虑我的ResourceFilter
/ AuthorizationFilter
执行和短路?
简短的回答是“你不能让ActionFilter
在AuhtorizeFilter
之前执行”。但是你可以将TimeRangeFilter
变成授权过滤器
public class TimeRangeFilterAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
public string AllowedMonths { get; set; } // like |3|4|5|
public string RedirectUrl { get; set; }
public void OnAuthorization(AuthorizationFilterContext context)
{
if (not allowed) {
context.Result = new RedirectResult(RedirectUrl);
}
}
}
指定Order = 0
使其在其他Authorize
检查之前运行,或者尝试不为它实现IOrderedFilter
,它也将首先执行。