将命令行参数传递给ASP Core中的Startup类 [英] Pass command-line arguments to Startup class in ASP Core
问题描述
我有通过命令行传递的参数
I have arguments passed in via the command-line
private static int Main(string[] args)
{
const string PORT = "12345" ;
var listeningUrl = $"http://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类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!