Custom WebApi AuthorizeAttribute
本文关键字:AuthorizeAttribute WebApi Custom | 更新日期: 2023-09-27 17:51:08
我有以下自定义授权属性:
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...
}
}
然而,我得到一个编译错误的'状态= canCreate':
非静态字段、方法或属性"CustomerController.canCreate"需要对象引用
有没有别的方法可以达到我想要做的?
不能在属性中使用变量。属性在编译时需要有一个静态值。您可以将静态值设置为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);
}