An Attribute Argument Must Be a Constant Expression, ...- Create an Attribute of Type Array

An attribute argument must be a constant expression , typeof expression or array creation expression of an attribute parameter type

You can't do that with attributes, they have to be constants as stated in the error message. If you wanted to get a value from the configuration file, you could do it by passing the key to the attribute, and then in the constructor get the value you want from the configurationmanager

    public MyAttribute :Attribute
{
private string _config;
public MyAttribute(string configKey)
{
_config = ConfigurationManager.AppSettings[configKey];

...
}
}

HTH

Custom attribute: An attribute argument must be a constant expression

I have updated my custom enum DescriptionAttribute to the following:

public class DescriptionWithValueAttribute : DescriptionAttribute
{
public Decimal Value { get; private set; }

public DescriptionWithValueAttribute(String description, Double value)
: base(description)
{
Value = Convert.ToDecimal(value);
}
}

It expects a Double then converts to Decimal, as I need the final value as a Decimal. Works as expected.

ASP.NET MVC - An attribute argument must be a constant expression

Attribute parameters are restricted to constant values of the following types:

  • Simple types (bool, byte, char, short, int, long, float, and double)
  • string
  • System.Type
  • enums
  • object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)
  • One-dimensional arrays of any of the above types

Reference: https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx

You can resolve your problem if you define SessionKeysConstants as an enum. And for that enum, one named constant is SMSNotificationsSearchClient.

As @StephenMuecke said above you can also make your string const too.

I would prefer an enum, this is somehow a standard if you're looking to data annotations(for example): https://msdn.microsoft.com/en-us/library/dd901590(VS.95).aspx

Basically your SessionKeysConstants is an enumeration of named constants, which by definition is an enum, but this is just my personal opinion.

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

A static string is not a constant.

Try changing

public static string AntiforgeryTokenSalt = "tokenFooYouTolkienBladeRunner"; 

to

public const string AntiforgeryTokenSalt = "tokenFooYouTolkienBladeRunner"; 


Related Topics



Leave a reply



Submit