我正在尝试为 ServiceStack 服务创建一个自定义属性,我可以使用它来控制服务类中的每个方法。
这是我正在实现的属性类。
[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class , Inherited = false, AllowMultiple = false)]
public class MyRequestFilterAttribute:RequestFilterAttribute
{
public string Provider { get; set; }
public MyRequestFilterAttribute(ApplyTo applyTo): base(applyTo)
{
this.Priority = (int) RequestFilterPriority.Authenticate;
}
public MyRequestFilterAttribute():this(ApplyTo.All)
{
}
public MyRequestFilterAttribute(ApplyTo applyTo, string provider): this(applyTo)
{
this.Provider = provider;
}
public MyRequestFilterAttribute(string provider): this(ApplyTo.All)
{
this.Provider = provider;
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{}
}
这是服务类
[MyRequestFilter(ApplyTo.All)]
public class TodoService : RestServiceBase<Todo>
{
public TodoRepository Repository { get; set; }
public override object OnGet(Todo request)
{
if (request.Id == default(long))
return Repository.GetAll();
return Repository.GetById(request.Id);
}
public override object OnPost(Todo todo)
{
return Repository.Store(todo);
}
public override object OnPut(Todo todo)
{
return Repository.Store(todo);
}
[MyRequestFilter("Admin")]
public override object OnDelete(Todo request)
{
Repository.DeleteById(request.Id);
return null;
}
public object GetDetailsofALL()
{
return null;
}
}
当我将属性放在类级别时,我能够控制方法。IE
[MyRequestFilter(ApplyTo.All)]
public class TodoService : RestServiceBase<Todo>{}
我需要的是在方法级别上也放置一个属性并进行一些身份验证,以便只有管理员有权执行此服务方法。但是,当我将此属性放在 Delete 方法中时,它不起作用,并且自定义过滤器属性没有被击中。只有类级别的属性调用有效。
[MyRequestFilter("Admin")]
public override object OnDelete(Todo request){}
是否可以从方法级别设置权限/过滤器属性?如果是,我该如何实施?