Can a filter access properties from my BaseController?

こ雲淡風輕ζ 提交于 2020-01-24 10:04:48

问题


I have a basecontroller that has a property like:

public class BaseController : Controller 
{
    public User CurrentUser {get;set;}

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // if session cookie found, set User object here
    }
}

Now I want to create an action filer that I could set on controllers or actions that I want to do something like:

if (User.IsAdmin) 
{
} 
else 
{
    // redirect to login or some page 
}

So this filter @AdminOnly I could put on a controller or action and this will ensure that only users who have the IsAdmin flag set will be able to view the action.

Does a filter have visibility into the currently executing controller?


回答1:


Can't you use

if (filterContext.Controller is BaseController)
{
    BaseController ctr = (BaseController)filterContext.Controller;
    if (ctr.User.IsAdmin)
    {....}
}

Link



来源:https://stackoverflow.com/questions/26023954/can-a-filter-access-properties-from-my-basecontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!