Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ActionName, ControllerName and AreaName and pass it in ActionFilter Attribute

I use a custom AuthorizationFilter like the followings:

public class ActionAuthorizeAttribute : AuthorizeAttribute {  protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {          if(!httpContext.User.Identity.IsAuthenticated)             return false;          if(IsUserExcluded())             return false;         else             return IsRoleAuthorize(httpContext);     } } 

I use this filter at the top of each action I have, and for check Is Authorized, need Action Name, Controller Name, And Area Name. So is there any way to get this names in AuthorizeCore() method like use System.Web.HttpContextBase? if answer is No then how can I get this names and pass it to attribute, obviously I don't want to add each name by hand, actually something likeViewContext.RouteData.Values["Controller"] in controllers:

[ActionAuthorize(actionName=Action, controller=ControllerName, area=AreaName)] public ActionResult Index() {     return View(); } 

Does any one have any idea about it?

like image 842
Saeid Avatar asked Apr 02 '12 12:04

Saeid


People also ask

How to apply action filter in MVC?

Mvc. FilterAttribute class. If you want to implement a particular type of filter, then you need to create a class that inherits from the base Filter class and implements one or more of the IAuthorizationFilter , IActionFilter , IResultFilter , or IExceptionFilter interfaces.

Which action filter triggers first?

The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called.

When to use result filter in MVC?

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, which derives from the ActionResult class. Example: public interface IResultFilter.

How the filters work in MVC architecture?

To create your own custom filter, ASP.NET MVC framework provides a base class which is known as ActionFilterAttribute. This class implements both IActionFilter and IResultFilter interfaces and both are derived from the Filter class.


1 Answers

You could fetch them from the RouteData:

protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {     var rd = httpContext.Request.RequestContext.RouteData;     string currentAction = rd.GetRequiredString("action");     string currentController = rd.GetRequiredString("controller");     string currentArea = rd.Values["area"] as string;      ...  } 
like image 50
Darin Dimitrov Avatar answered Oct 04 '22 14:10

Darin Dimitrov