[英]I can't decorate whole Controller with my Custom Authorize Attribute
I try to decorate a full controller class like this: 我尝试装饰一个完整的控制器类,如下所示:
namespace SisParkTD.Controllers
{
[CustomAuthorize]
public class AbonosController : Controller
{
I can decorate the methods in the controller but can't decorate the full controller. 我可以装饰控制器中的方法,但不能装饰完整的控制器。
The error i get when i try to decorate the controller class is this: 我尝试装饰控制器类时得到的错误是这样的:
The attribute 'CustomAuthorize' is not valid on this declaration type.
属性“CustomAuthorize”在此声明类型上无效。 It is only valid on 'method' declarations.
它仅对'方法'声明有效。
Attribute 'SisparkTD.Filters.CustomAuthorizeAttribute' is not valid on this declaration type.
属性'SisparkTD.Filters.CustomAuthorizeAttribute'在此声明类型上无效。 Is is valid on 'Method' declarations only.
仅在“方法”声明中有效。
Here is the code for the CustomAuthorizeAttribute: 以下是CustomAuthorizeAttribute的代码:
namespace SisParkTD.Filters
{
[AttributeUsage(AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
using (var db = new SpContext())
{
var controller = (string)httpContext.Request.RequestContext.RouteData.Values["controller"];
var action = (string)httpContext.Request.RequestContext.RouteData.Values["action"];
var accion = db.Acciones.FirstOrDefault(a => a.Descripcion == action && a.Pagina.Descripcion == controller);
var username = httpContext.User.Identity.Name;
var usuario = db.Usuarios.FirstOrDefault(u => u.NombreDeUsuario == username);
if (usuario == null) return false;
if (accion == null) return false;
var rolesId = db.RolesUsuarios.Where(ru => ru.UsuarioId == usuario.UsuarioId).Select(ru => ru.RolId);
if (!rolesId.Any()) return false;
foreach (var rolId in rolesId)
{
if (db.Permisos.Find(rolId, accion.AccionId) != null) return base.AuthorizeCore(httpContext);
}
return false;
}
}
}
}
Remove [AttributeUsage(AttributeTargets.Method)] from the attribute. 从属性中删除[AttributeUsage(AttributeTargets.Method)]。 (credit to SLaks for the answer)
(感谢SLaks的回答)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.