Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array as a command line argument to Asp.Net Core

Need to pass array as a command line argument to Asp.Net Core hosted service.

Added providers

config
  .AddJsonFile("appsettings.json")
  .AddCommandLine(args);

somewhere in application I have

var actions = _configuration.GetSection("actions").Get<List<string>>();
foreach (var action in actions)
{
   Console.WriteLine(action);
}

Try to run app like

dotnet MyService.dll --actions Action1,Action2
dotnet MyService.dll --actions [Action1,Action2]
dotnet MyService.dll --actions ["Action1","Action2"]

but no results, the actions is null

When I add "actions": ["Action1","Action2"] to appsettings.json then binding works well.

How to pass array as a command line argument?

I can get it in this way _configuration.GetValue<string>("actions").Split(",");, but how to bind it to list?

like image 258
Roman Marusyk Avatar asked Nov 22 '19 15:11

Roman Marusyk


People also ask

How do you pass an array to a method in C#?

You can pass an initialized single-dimensional array to a method. For example, the following statement sends an array to a print method. int[] theArray = { 1, 3, 5, 7, 9 }; PrintArray(theArray); The following code shows a partial implementation of the print method.

Does C# pass array by reference?

In C#, arrays are the reference types so it can be passed as arguments to the method. A method can modify the value of the elements of the array. Both single-dimensional and multidimensional arrays can be passed as an argument to the methods.


1 Answers

ASP.NET Core configuration is a set of key-value pairs. The appsettings.json property you've shown gets converted into the following:

  • actions:0 = Action1
  • actions:1 = Action2

Provide this same set of key-value pairs as multiple command-line arguments to get the desired result:

dotnet MyService.dll --actions:0 Action1 --actions:1 Action2
like image 66
Kirk Larkin Avatar answered Oct 03 '22 17:10

Kirk Larkin