How can I set an attribute name property from static data in C#:
[FaraAuthorize(Roles = RoleValues.SiteManager)] // Error here
public class ProjectsController : FaraController
{
}
public static class RoleValues
{
static RoleValues()
{
using (var db = FaraIdentityEntity.GetEntity())
{
SiteManager = db.Roles.Single(item => item.Name == "SiteManager").Id;
}
}
public static string SiteManager = "";
}
Error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter
I can make SiteManager
a const
field but then I can't set the value of SiteManager
in the static constructor. How to solve this problem?
You can't, basically. Attribute values are embedded directly in the compiled assembly - they can't be determined at execution time. If you need information which is only available at execution time, you'll need a different approach which doesn't require that information to be present in attribute values.
(Well, you could generate the types on the fly with the relevant attribute data, but that's likely to be harder than any other approach...)
See more on this question at Stackoverflow