Paul Johnson
Paul Johnson

Reputation: 1418

Is there a way a c# attribute can be sent a parameter from the method it is used on

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

Answers (2)

jrummell
jrummell

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

C.Evenhuis
C.Evenhuis

Reputation: 26436

The attribute is associated with the method - not to a method call and its parameters.

Upvotes: 1

Related Questions