MVC Action Filters using parameters passed to the for ActionResult?
Asked Answered
S

2

12

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?

Scotch answered 30/8, 2012 at 18:36 Comment(1)
I do not think there is a way to access the USER Id being passed into that parameter. There is probably a way to access the USER id of the user logged in to your system though. And you may be able to access anything in the View data ... but I wouldn't recommend going that route even if you could.Keynes
B
13

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!            
            }
        }
    }
} 
Bock answered 30/8, 2012 at 18:51 Comment(0)
N
0

You can create a custom attribute which derives from FilterAttribute and implements IAuthorizationFilter.

You should also be able to get the user information in the OnAuthorization method by accessing filterContext.HttpContext.User.Identity without the need to pass the userid.

Nuclear answered 30/8, 2012 at 18:45 Comment(1)
I don't think he's necessarily looking for the logged in users id, it looks more like he's making an admin page to view any user.Methacrylate

© 2022 - 2024 — McMap. All rights reserved.