【问题标题】:When apply an attribute in class and method together, How to force use method attribute?在类和方法中同时应用属性时,如何强制使用方法属性?
【发布时间】:2016-07-18 13:04:20
【问题描述】:

我有一个属性来检查控制器操作中的身份验证。我的属性是这样的:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthenticationRequiredAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    private readonly bool checkAuthentication;
    public AuthenticationRequiredAttribute(bool checkAuthentication)
    {
        this.checkAuthentication = checkAuthentication;
    }

    public void OnAuthentication(AuthenticationContext filterContext)
    {
        if (checkAuthentication && !UserIdentity.IsAuthenticated)
            filterContext.Result = new HttpUnauthorizedResult(); 
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.Result = new RedirectToRouteResult(
                        new System.Web.Routing.RouteValueDictionary{
                                        {"controller", "Account"},
                                        {"action", "Login"}
                                    });
        }
    }
}

如果checkAuthentication = false 不检查认证。 除一项操作外,控制器中的所有操作都应检查身份验证。我在控制器上应用[AuthenticationRequired(true)],在特定操作上应用[AuthenticationRequired(false)]。但它不起作用,总是检查身份验证。 当将[AuthenticationRequired(true)] 应用于其他操作并将其从控制器中删除时,它可以正常工作。

在这种情况下如何强制使用方法属性?

【问题讨论】:

  • 你能给我们检查属性的代码吗?
  • @LuisFilipe 我编辑我的问题并添加属性代码。
  • 你想要什么?默认的 Authorize Attribute 不支持这样的事情并且有一个不同的属性:AllowAnonymous..see code here github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/… and see SkipAuthorization function 也许你也可以在你的场景中应用这种解决方案

标签: c# asp.net-mvc custom-attributes actionfilterattribute


【解决方案1】:

修改您的OnAuthentication 并添加AllowAnonymous 属性的验证。

bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                 || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

        if (skipAuthorization)
        {
            return;
        }

之后,只需将AllowAnonymous 属性添加到应该跳过身份验证\授权的方法。

【讨论】:

    【解决方案2】:

    如果您应用控制器级别的过滤器,则它适用于所有操作并覆盖任何同名过滤器。

    您可以将过滤器应用于每个操作,或尝试使用已接受的答案here。这将让您指定要排除的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-23
      • 2010-09-06
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多