Restricted Attribute did not register in Startup.Cs

455 Views Asked by At

I have a restricted attribute class in Asp.net Core 2.0 project and I decorate my controller with this attribute but this class is not executing when I run the project I also put debug point on it here I am register this attribute

 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 } }
1

There are 1 best solutions below

2
On BEST ANSWER

The declaration for your RestrictedAttribute is incorrect. You only need to derive from the ActionFilterAttribute class as that already derives from the IActionFilter interface.

And in your class you need to override the OnActionExecuting of the ActionFilterAttribute class and not implement the interface method i.e. you should not have IActionFilter.OnActionExecuting as that is not the method that needs to be implemented.

The correct implementation is:

public class RestrictedAttribute : ActionFilterAttribute
{
     public override void OnActionExecuting(ActionExecutingContext filterContext)
     { 
        //Other Code 
     }
}

In addition, you don't need to add the filter to the config.Filters in AddMvc(). It will work without that :-)