Had a similar requirement where I had to pass along a value to a custom attribute.
The issue here is that Attribute decorations don't allow variables.
You get compile time error:
An object reference is required for the non-static field, method, or
property
Here is how I was able to do it:
In Controller
[FineGrainAuthorization]
public class SomeABCController : Controller
{
public int SomeId { get { return 1; } }
}
In Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class FineGrainAuthorizationAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
ControllerBase callingController = filterContext.Controller;
var someIdProperty = callingController.GetType().GetProperties().Where(t => t.Name.Equals("SomeId")).First();
int someId = (int) someIdProperty.GetValue(callingController, null);
}
}
Remember that the string inside .Name.Equals("SomeId") must case match the declaration public int SomeId