I defined the following custom attribute:
[AttributeUsage(AttributeTargets.All)]
public class CustomAuthAttribute : AuthorizeAttribute
{
private MyPermissionLevels requestedAccessLevel;
public CustomAuthAttribute(object AccessLevel = null)
{
AccessLevel = AccessLevel ?? MyPermissionLevels.View;
if(AccessLevel.GetType() != typeof(MyPermissionLevels))
{
throw new ArgumentException("AccessLevel is invalid.");
}
this.requestedAccessLevel = (MyPermissionLevels)AccessLevel;
}
... // Other Auth Stuff
}
When I apply this attribute to a controller as, for example, [CustomAuthAttribute (AccessLevel = MyPermissionLevels.Modify)]
intellisense complains that:
The type or namespace name 'AccessLevel' could not be found. (etc?)
The potential fixes revealed by Alt + Enter include:
Change 'AccessLevel' to 'AccessLevel:'
Adding this colon (and by implication removing the =
operator, which is not an automagical part of the suggested fix) does resolve the compilation error.
I am okay using a different syntax if that's all that need be. However, I would like to understand what I've done that prevents me from using the more common attribute field-initialization syntax as described in answers to Named parameters confusion and as can be done with the parent class:
[Authorize(Roles = "Modifiers")]
The colon is necessary because that is the syntax for named parameters. The field isn't public, nor are you trying to assign to it. The field's name is requestedAccessLevel
, not AccessLevel
.
The parent class has a public property Roles
, so in the line:
[Authorize(Roles = "Modifiers")]
Roles
is not a named constructor parameter, it's a property, so named parameter syntax is not used. Indeed, that attribute doesn't have a constructor that accepts parameters. It only has public, assignable properties.