将命令行参数传递给ASP Core中的Startup类

编程入门 行业动态 更新时间:2024-10-25 09:36:01
本文介绍了将命令行参数传递给ASP Core中的Startup类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有通过命令行传递的参数

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类

本文发布于:2023-11-16 07:44:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602336.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令行   参数   ASP   Core   Startup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!