首页 > 解决方案 > 如何根据条件使用属性。(通过标志禁用)

问题描述

我正在使用来自:System.Web.Http

基本控制器的属性。

问题是我需要根据条件使用它。

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

我怎样才能实现它?

谢谢。

标签: c#asp.net-web-api2custom-attributes

解决方案


一种方法是覆盖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()
{
    ...
}

推荐阅读