我有以下自定义授权属性:
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'
还有另一种方法可以实现我想要做的事情吗?
答案 0 :(得分: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);
}