Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionFilterAttribute - apply to actions of a specific controller type

I'm using an ActionFilterAttribute to do custom authentication logic. The Attribute will only be used on a derived Controller class that contains my authentication logic.

Here's my Controller, derived from my custom controller class, and a sample attribute:

public class MyController : CustomControllerBase
{

   [CustomAuthorize(UserType = UserTypes.Admin)]
   public ActionResult DoSomethingSecure()
   {
      return View();
   }

}

Here's an example of my ActionFilterAttribute:

public class CustomAuthorizeAttribute : ActionFilterAttribute
{
   public MyUserTypes UserType { get; set; }

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      myUser user = ((CustomControllerBase)filterContext.Controller).User;

      if(!user.isAuthenticated)
      {
         filterContext.RequestContext.HttpContext.Response.StatusCode = 401;
      }
   }
}

Works great.

Here's the question: Can I demand that this attribute ONLY be used on Actions in my custom controller type?

like image 537
Peter J Avatar asked Sep 17 '09 17:09

Peter J


People also ask

Which of these functions can be overridden when deriving a class from ActionFilterAttribute?

The ActionFilterAttribute abstract class includes the following methods to override: void OnActionExecuted(ActionExecutedContext filterContext) void OnActionExecuting(ActionExecutingContext filterContext) void OnResultExecuted(ResultExecutedContext filterContext)

What is ActionFilterAttribute in MVC?

Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called before and after the action starts executing and after the action has executed. Action filters implement the IActionFilter interface that has two methods OnActionExecuting andOnActionExecuted.

What step is required to apply a filter globally to every action in your application?

You need to add your filter globally, to add your filter to the global filter. You first need to add it on Global. asax file. You can use FilterConfig.


1 Answers

You can put the ActionFilter on the class itself. All actions in the class will realize the ActionFilter.

[CustomAuthorize]
public class AuthorizedControllerBase : CustomControllerBase
{
}

public class OpenAccessControllerBase : CustomControllerBase
{
}

public class MyRealController : AuthorizedControllerBase 
{
    // GET: /myrealcontroller/index
    public ActionResult Index()
    {
        return View();
    }
}
like image 149
Jarrett Meyer Avatar answered Oct 02 '22 10:10

Jarrett Meyer