【问题标题】:How to use attributes based on condition. (disable by a flag)如何根据条件使用属性。 (通过标志禁用)
【发布时间】:2019-02-24 10:01:16
【问题描述】:

我正在使用“授权” 来自:System.Web.Http

基本控制器的属性。

问题是我需要根据情况使用它。

(假设我有一个不需要身份验证/授权的模式)。

我怎样才能实现它?

谢谢。

【问题讨论】:

    标签: c# asp.net-web-api2 custom-attributes


    【解决方案1】:

    一种方法是覆盖AuthorizeAttribute,并在其中添加自定义逻辑。 这里我们有两种情况,如果你想将它与MVC 控制器一起使用覆盖AuthorizeCore() 方法并使用System.Web.Mvc 命名空间,如下所示:

    public class MyCustomAuthorizeAttribute: AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            bool isExceptionalCase = GetIfExceptional();//Assuming here where you look for some other condition other than user is authorized
            if (!isExceptionalCase && !authorized)
            {
                // The user is not authorized => no need to go any further
                return false;
            }
    
            return true;
        }
    }
    

    第二种情况,在您的情况下,您将使用 WebApi 控制器,您可以覆盖 IsAuthorized() 并使用 System.Web.Http 命名空间:

    public class MyCustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var authorized = base.IsAuthorized(actionContext);
            bool isExceptionalCase = GetIfExceptional();//Assuming here where you look for some other condition other than user is authorized
            if (!isExceptionalCase && !authorized)
            {
                // The user is not authorized => no need to go any further
                return false;
            }
    
            return true;
        }
    }
    

    然后在动作或控制器上使用自定义属性,而不是使用标准属性:

    [MyCustomAuthorize]
    public ActionResult MyAction()
    {
        ...
    }
    

    【讨论】:

    • 嗨 - 你的意思是覆盖受保护的覆盖 bool IsAuthorized(HttpActionContext actionContext)?
    • override bool AuthorizeCore 不适合你? @user10776203
    • 我在看@System.Web.Http 版本 5.2.3.0 并没有看到这样的方法
    • @user10776203 查看更新的答案,希望对您有所帮助
    【解决方案2】:

    您可以在特定方法或控制器中使用 AllowAnonymousAttribute 来“覆盖”基本控制器中使用的 AuthorizeAttribute。

    查看参考:https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835113(v%3dvs.118)

    作为另一种选择,您可以创建自定义属性并在基本控制器中使用它。通过这种方式,您可以在自定义属性中添加做出决策所需的所有逻辑。

    查看参考:https://docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes

    问候,洛杉矶。

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 2021-11-04
      • 2021-12-11
      • 2021-09-06
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      相关资源
      最近更新 更多