C# 受限属性未在Startup.Cs中注册
我在Asp.net Core 2.0项目中有一个受限制的属性类,我用这个属性装饰我的控制器,但是当我运行这个项目时,这个类没有执行,我还对它设置了调试点 我在这里注册这个属性C# 受限属性未在Startup.Cs中注册,c#,asp.net-core,authorize-attribute,global-filter,C#,Asp.net Core,Authorize Attribute,Global Filter,我在Asp.net Core 2.0项目中有一个受限制的属性类,我用这个属性装饰我的控制器,但是当我运行这个项目时,这个类没有执行,我还对它设置了调试点 我在这里注册这个属性 services.AddMvc(config => { config.Filters.Add(typeof(RestrictedAttribute)); }); [Area("Admin")] [Restricted] public class Medi
services.AddMvc(config =>
{
config.Filters.Add(typeof(RestrictedAttribute));
});
[Area("Admin")]
[Restricted]
public class MediaController : Controller
{}
public class RestrictedAttribute : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{ //Other Code } }
RestrictedAttribute
的声明不正确。您只需要从ActionFilterAttribute
类派生,因为该类已经从IActionFilter
接口派生
在您的类中,您需要覆盖ActionFilterAttribute
类的OnActionExecuting
,而不实现接口方法,即您不应该使用IActionFilter.OnActionExecuting
,因为这不是需要实现的方法
正确的实施方式是:
public class RestrictedAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Other Code
}
}
此外,您不需要将过滤器添加到
AddMvc()
中的config.Filters
。如果没有它,它将工作:-)我尝试添加一个继承自ActionFilterAttribute的类,但没有修改Startup.cs,并且我的OnActionExecuting方法从未被命中。有什么想法吗?如果不使用AddMvc()
,如何访问config.Filters
?