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?
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.
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.
ASP.NET Core configuration is a set of key-value pairs. The appsettings.json property you've shown gets converted into the following:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With