I just want don't use "Managers" for each attribute and use some enum for that.
But it seems it is impossible or I am wrong?
So I try to replace
[RequiresRole("Managers")]
with
[RequiresRole(HardCodedRoles.Managers.ToString())]
...
public enum HardCodedRoles
{
Administrators,
Managers
}
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).
An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum's element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined.
Let's try our extension method. var status = TransactionStatus. ForApproval; status. GetDisplayName();
Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.
How about a class instead of an enum, making the class static to avoid somebody new:ing it ?
public static class HardCodedRoles
{
public const string Managers = "Managers";
public const string Administrators = "Administrators";
}
[RequiresRole(HardCodedRoles.Managers)]
You could also use the nameof keyword, i.e.:
[RequiresRole(nameof(HardCodedRoles.Managers))]
The reason you see the error is because ToString()
is a method and thus the value cannot be calculated at compile time.
If you can use [RequiresRole(HardCodedRoles.Managers)] instead, you can perform the ToString
elsewhere in your code, and this could give you the functionality you need. This will require that you change the parameter of your attribute from string
to HardCodedRoles
.
(I would imagine that using a const
won't work, because the type of the parameter will still be string
, so the input won't be restricted.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With