我有通过命令行传递的参数
I have arguments passed in via the command-line
private static int Main(string[] args) { const string PORT = "12345" ; var listeningUrl = $"localhost:{PORT}"; var builder = new WebHostBuilder() .UseStartup<Startup>() .UseKestrel() .UseUrls(listeningUrl); var host = builder.Build(); WriteLine($"Running on {PORT}"); host.Run(); return 0; }这些参数之一是日志记录输出目录.如何在我的Startup类中获取此值,以便在收到请求时可以写出该目录?
One of these arguments is a logging output directory. How do I get this value into my Startup class so I can write out to this directory when I receive a request?
我想避免使用静态类.提供价值的服务是否正确?如果是这样,我如何将服务注入到我的中间件中?
I'd like to avoid using a static class. Would a service that supplies the value be the right way? If so, how do I get services injected into my middleware?
推荐答案您应该可以使用AddCommandLine()扩展名.首先安装Nuget软件包Microsoft.Extensions.Configuration.CommandLine并确保导入正确:
You should be able to use the AddCommandLine() extension. First install the Nuget package Microsoft.Extensions.Configuration.CommandLine and ensure you have the correct import:
using Microsoft.Extensions.Configuration;现在更新您的Main方法以包括新的配置:
Now update your Main method to include the new config:
var config = new ConfigurationBuilder() .AddJsonFile("hosting.json", optional: true) //this is not needed, but could be useful .AddCommandLine(args) .Build(); var builder = new WebHostBuilder() .UseConfiguration(config) //<-- Add this .UseStartup<Startup>() .UseKestrel() .UseUrls(listeningUrl);现在,您将命令行选项视为配置:
Now you treat the command line options as configuration:
dotnet run /MySetting:SomeValue=123并阅读代码:
var someValue = Configuration.GetValue<int>("MySetting:SomeValue");更多推荐
将命令行参数传递给ASP Core中的Startup类
发布评论