将数组作为命令行参数传递给Asp.Net Core

10
需要将数组作为命令行参数传递给Asp.Net Core托管服务。
已添加的提供程序。
config
  .AddJsonFile("appsettings.json")
  .AddCommandLine(args);

我在应用程序中的某个地方有一个

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

尝试运行应用程序,如下所示:
dotnet MyService.dll --actions Action1,Action2
dotnet MyService.dll --actions [Action1,Action2]
dotnet MyService.dll --actions ["Action1","Action2"]

但没有结果,actionsnull

当我在appsettings.json中添加"actions": ["Action1","Action2"]时,绑定就正常工作了。

如何将数组作为命令行参数传递?

我可以通过这种方式获取它:_configuration.GetValue<string>("actions").Split(",");,但如何将它绑定到列表中?

1个回答

13

ASP.NET Core配置是一组键值对。你展示的appsettings.json属性会被转换为以下内容:

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

要获得所需结果,可以将此相同的键值对作为多个命令行参数提供:

dotnet MyService.dll --actions:0 Action1 --actions:1 Action2

官方文档提供了更多细节:https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration-providers#command-line-arguments - Alex Klaus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接