【问题标题】:Pass array as a command line argument to Asp.Net Core将数组作为命令行参数传递给 Asp.Net Core
【发布时间】:2020-03-18 17:22:58
【问题描述】:

需要将数组作为命令行参数传递给 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

当我将 "actions": ["Action1","Action2"] 添加到 appsettings.json 时,绑定效果很好。

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

_configuration.GetValue&lt;string&gt;("actions").Split(",");这种方式可以得到,但是如何绑定到list呢?

【问题讨论】:

    标签: c# asp.net-core .net-core command-line-arguments


    【解决方案1】:

    ASP.NET Core 配置是一组键值对。您显示的 appsettings.json 属性将转换为以下内容:

    • 动作:0 = 动作1
    • 动作:1 = 动作2

    提供这组相同的键值对作为多个命令行参数以获得所需的结果:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-07
    • 2012-03-25
    • 2020-01-06
    • 1970-01-01
    • 2012-08-13
    • 2017-11-30
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多