【问题标题】:Custom WebApi AuthorizeAttribute自定义 WebApi AuthorizeAttribute
【发布时间】:2014-03-20 11:57:54
【问题描述】:

我有以下自定义授权属性:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public ActionsEnum Action;
    public bool State;

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);

        //Custom validation here...

        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
    }
}

我也有这个控制器:

public class CustomerController : ApiController
{
    private bool canCreate, canUpdate, canDelete;

    public CustomerController()
    {
        //Dummy values
        canCreate = true;
        canUpdate = true;
        canDelete = false;
    }

    [CustomAuthorize(Action = ActionsEnum.Create, State = canCreate)]
    public HttpResponseMessage PostCustomer(CustomerDTO customer)
    {
        //Code...
    }

    public HttpResponseMessage PutCustomer(CustomerDTO customer)
    {
        //Code...
    }

    public HttpResponseMessage DeleteCustomer(int id)
    {
        //Code...
    }
}

但是,我在“State = canCreate”上遇到编译错误:

非静态字段、方法或属性“CustomerController.canCreate”需要对象引用

还有其他方法可以实现我想要做的事情吗?

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    您不能在属性中使用变量。属性在编译时需要有一个静态值。您可以将静态值设置为 state:

    [CustomAuthorize(Action = ActionsEnum.Create, State = true)]
    

    或者在你的属性中获取这些值

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);
    
        var canX = // Get value here
        //Custom validation here...
    
        HandleUnauthorizedRequest(actionContext);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2020-09-08
      • 1970-01-01
      • 2014-12-23
      • 2012-03-17
      相关资源
      最近更新 更多