开发者

Disallow all pages except specific pages with ActionFilter

开发者 https://www.devze.com 2023-04-10 02:07 出处:网络
I have an ActionFilter that is applied to my base controller which checks certain things in the request and session and makes sure that you are allowed to view the requested URI.

I have an ActionFilter that is applied to my base controller which checks certain things in the request and session and makes sure that you are allowed to view the requested URI.

This has worked fine until now when we need to disallow all pages (as it exists today) but allow a few URIs here and there.

Ideally, I would apply an attribute to the ones that we want to allow and then check for that attribute in the filter and allow if it exists, but I cannot figure out how to make that happen in the filter.

Any ideas or sug开发者_运维知识库gestions?


I spent over an hour trying to figure this out then I posted here on SO. Minutes later, it hit me.

First, I created an attribute

public class AlwaysAllowAnonymousAttribute : Attribute {}

Second I marked my action or controller with the above attribute

Finally, in my ActionFilter i did this

public class VerifyResourceAccess : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {

        var actionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AlwaysAllowAnonymousAttribute), false);
        var controllerAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AlwaysAllowAnonymousAttribute), false);
        bool alwaysAllow = (actionAttributes.Length > 0) || (controllerAttributes.Length > 0);

        if (!alwaysAllow) {
            /* ... Some logic for checking if this user is allowed to access this resource  ... */
        }

        base.OnActionExecuting(filterContext);
    }
}

Any action or controller that is marked with the attribute will always have access allowed to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消