Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Action Filters using parameters passed to the for ActionResult?

I created a custom Action Filter with no problem.

But I would like to modify the Action Filter to use some of the parameters actually passed to my method.

So if I have the following method:

[HttpPost]
[MyAttribute]
public ActionResult ViewUserDetails(Guid userId)
{
     // Do something
}

How can I get access to userId from within MyAttribute? Is there a way I can directly pass it in?

like image 503
Kyle Avatar asked Aug 30 '12 18:08

Kyle


1 Answers

You can try OnActionExecuting override, where you do have access to action parameters.

public class MyAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {    
        if (filterContext.ActionParameters.ContainsKey("userId"))
        {
            var userId = filterContext.ActionParameters["userId"] as Guid;
            if (userId != null)
            {
                // Really?! Great!            
            }
        }
    }
} 
like image 103
danielQ Avatar answered Oct 21 '22 06:10

danielQ