Reputation: 1418
How can I pass into an attribute a parameter that was sent to the function that this attribute was used on? e.g. I need to do something like this...
[Authorize, AuthorizeLimited( ModuleID=pageModuleId)]
[HttpPost]
public ActionResult MoveModule(int pageModuleId, int sequence)
{
db.PageModule_Move(pageModuleId, sequence);
return Json("OK");
}
The pageModuleId sent to the method must also go to the attribute. Sorry if this has already been asked I couldn't find an answer.
EDIT
OK using the answer provided by @jrummell here is my first action filter attribute :) This is simply to stop someone editing a module (used by ajax) who does not have the perms.
public class AuthorizeModuleEditAttribute : ActionFilterAttribute
{
private int _moduleID;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
foreach (var parameter in filterContext.ActionParameters)
{
if (parameter.Key == "pageModuleId")
{
_moduleID = (int)filterContext.ActionParameters["pageModuleId"];
}
}
if (!SiteHelper.UserPermsForModule(_moduleID)) //checks if user has perms to edit module
throw (new Exception("Invalid user rights"));
base.OnActionExecuting(filterContext);
}
}
Upvotes: 0
Views: 135
Reputation: 43067
No, attribute parameter values must be compile time constants.
However, if you implement your own action filter, you can override OnActionExecuting
and inspect the action parameters in filterContext.ActionParamters
.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
foreach(var parameter in filterContext.ActionParameters)
{
if (parameter.Key == "pageModuleId")
{
// do something with pageModuleId
}
}
base.OnActionExecuting(filterContext);
}
Upvotes: 4
Reputation: 26436
The attribute is associated with the method - not to a method call and its parameters.
Upvotes: 1