Should I call base.OnAuthorization(filterContext)?

2019-05-27 09:39发布

问题:

I have a custom AuthorizeAttribute like so:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAuthenticated)
    {
        var userInRole = CurrentUser.IsInRole(Roles);

        // Etc...
    }
}

Should I be calling base.OnAuthorization(filterContext) at all here?

If so, what would it do?

回答1:

The default implementation is open source and can be viewed here.

It checks whether the user is authenticated, then checks to ensure the user or role is specified on the attribute.

I guess the real question is, why are you writing a custom AuthorizeAttribute when the built-in one already does what you are doing?

Do note that it would be simpler to override the AuthorizeCore method (instead of OnAuthorization) if you really do need to customize it because the OnAuthorization method has code to disable output caching so cached views cannot be seen after logout.