Activities with children are not allowed to perform a redirect exception in filters added to Global Filters

I am trying to implement the pass-through authorize attribute, but I am getting an exception -

Exception: Child actions are not allowed to perform redirect actions

      

Here is my code:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MyAuthorizeAttribute(new List<string>(), new List<string>()));
    }
}

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    public MyAuthorizeAttribute(IEnumerable<string> permittedRoles = null, IEnumerable<string> permittedUsers = null)
    {
        if (permittedRoles != null) Roles = string.Join(",",permittedRoles);
        if (permittedUsers != null) Users = string.Join(",",permittedUsers);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
            new RedirectToRouteResult(new RouteValueDictionary
            {
                {"controller", "NotAuthorized"},
                {"action", "Index"}
            });
    }
}

      

Is there anything I can do that will allow me to continue to use it MyAuthorizeAttribute

as a global filter?

+3


source to share


1 answer


Add the following snippet to the beginning HandleUnauthorizedRequest

:

if (filterContext.IsChildAction)
{
     return;
}

      



This will undo the redirection for child activities.

Alternatively, you can disable the attribute for all child-only controllers using [AllowAnonymous]

. It can also be used to decorate your "unauthorized" controller to stop the redirection.

+1


source







All Articles