MVC Action Filters using parameters passed to the

2019-04-05 04:13发布

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?

2条回答
We Are One
2楼-- · 2019-04-05 04:44

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-05 04:46

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!            
            }
        }
    }
} 
查看更多
登录 后发表回答