How to pass attribute parameter type using List <string> in C #?

How to pass a list to a constructor?

The message is displayed here:

Error 14 The attribute argument must be a constant expression, a type expression, or an expression expression of an array of attribute parameter type

public class CustomAuthorize : AuthorizeAttribute {
    private List<string> multipleProgramID;

    //constructor
    public CustomAuthorize(List<string> _multipleProgramID) {
        multipleProgramID = _multipleProgramID;
    }
}

[CustomAuthorize(new List<string>(new string[] { ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT } ))]
[HttpPost]
public ActionResult DeleteWaterQualityItems(string sourceID, string wqID) {
    // ..other code...
}

public class ProgramList {
    public const string SURVEY_INPUT = "A001";
    public const string SURVEY_INPUT = "A002";
}
+4
source share
4 answers

The problem is not passing List<string>to the constructor at all - the problem is that you are trying to use it for an attribute. You basically cannot do this because it is not a compile-time constant.

It looks like ProgramList- this is really enum - so you can make it enum instead:

 [Flags]
 public enum ProgramLists
 {
     SurveyInput,
     SurveyOutput,
     ...
 }

CustomAuthorizeAttribute ( , Attribute) ProgramLists . :

[CustomAuthorize(ProgramLists.SurveyInput | ProgramLists.SurveyOutput)]

ProgramLists , "A001". , , , - Dictionary<ProgramLists, string>.

, CustomAuthorizeAttribute , , :

[AttributeUsage(AttributeTargets.Method)]
public class FooAttribute : Attribute
{
    public FooAttribute(params string[] values)
    {
        ...
    }
}

[Foo("a", "b")]
static void SomeMethod()
{
}
+8

List <T> .

, . MSDN -

:

//constructor
public CustomAuthorize(string[] _multipleProgramID) 
{
    ...
}

// usage
[CustomAuthorize(new string[] { ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT })]
+3

You just need to use the "params" keyword in your custom attribute constructor and make your list "enum" for the list of programs

[CustomAttribute(ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT)]
[HttpPost]
public ActionResult DeleteWaterQualityItems(string sourceID, string wqID) {
    // ..other code...
}

in your custom attribute class use this

public class CustomAuthorize : AuthorizeAttribute {

//Constructor
public CustomAuthorize (params ProgramList[] programListTypes) {

            multipleProgramID= programListTypes;
        }

private ProgramList[] multipleProgramID;

}

and you list the class

public enum ProgramList : int
{
SURVEY_INPUT = 001;
SURVEY_OUTPUT =002;

}
+1
source

I tried to do something similar and ended up passing the comma separated stringand using the string.Spilt(',')attribute in the constructor to convert it to an array.

0
source

All Articles