Search code examples
c#asp.netasp.net-coreclaimsclaims-authentication

How to add new claims to claim array using foreach loop in C#?


I want to add new claims to a claim array in a foreach loop. How to do that?

        //userRoles is a list of string contains roles. 
        var userRoles = _repository.GetRolesOfUser(username); 
        var claim = new[]
        {
            new Claim("username", username)
                                                 
        };
        //I want to add new claims to claim like below. 
        //When I put Add I am getting error like this
        // "Claim[] doesn't contain definition for Add." 
        foreach(var userRole in userRoles)
        {
            claim.Add(new Claim("roles", userRole)); 
        }

What I want at the end is something like this where Role_1, Role_2 etc are from the userRole list.

var claim = new[]
            {
                new Claim("username", username)                    
                new Claim("roles", "Role_1")
                new Claim("roles", "Role_2")
                new Claim("roles", "Role_3")
                new Claim("roles", "Role_4")
             }

Solution

  • As John says, the array in C# doesn't contain add method. It only contains append method.

    If you want to add new element into array, you should use append instead of add.

    More details, you could refer to below test demo codes:

            var claims = new[]{
            new Claim("username", "aaa")
    
        };
            claims.Append(new Claim("aaa","aaa"));
    

    Your codes should like this:

        //userRoles is a list of string contains roles. 
        var userRoles = _repository.GetRolesOfUser(username); 
        var claim = new[]
        {
            new Claim("username", username)
                                                 
        };
        //I want to add new claims to claim like below. 
        //When I put Add I am getting error like this
        // "Claim[] doesn't contain definition for Add." 
        foreach(var userRole in userRoles)
        {
            claim .Append(new Claim("roles", userRole));
        }
    

    Or you could use List<Claim> instead of var claims = new[], like below:

            var claim = new List<Claim>();
    
            claim.Add("username", "aaa");
            claim.Add("username", "bbbb");