[英]How do I access command line parameters in an ASP.NET Core MVC app?
My goal is to use arguments from the command line (namely, a username + token) later in one of the controllers. 我的目标是稍后在其中一个控制器中使用命令行中的参数(即用户名+令牌)。
--environment
. --environment
之外的自定义参数。 Ultimately I need to have some value configured at the beginning of the app, and this value needs to be accessed by controller methods later. 最终,我需要在应用程序的开头配置一些值,稍后需要通过控制器方法访问此值。 Any alternatives that achieve this are also greatly appreciated.
任何实现这一目标的替代方案也非常受欢迎。
ASP.NET Core is shipped with built-in DI container , that should be used for dependency resolving via constructor parameters. ASP.NET Core附带内置的DI容器 ,应该用于通过构造函数参数进行依赖性解析。
I've found ways to pass command line arguments into the Startup class , but not how to get it into the controller.
我已经找到了将命令行参数传递到Startup类的方法 ,但没有找到如何将它传入控制器的方法。
This example already has everything that you need. 这个例子已经包含了你需要的一切。 See:
看到:
.ConfigureServices(services => services
.AddSingleton(new ConsoleArgs(args))
this line register ConsoleArgs
instance as a Singleton to DI container. 此行将
ConsoleArgs
实例注册为Singleton到DI容器。 Then it could be used as the dependency in any class. 然后它可以用作任何类中的依赖项。 Like into
Startup
class in linked example: 就像链接示例中的
Startup
类一样:
// args will be resolved using DI container
public Startup(IHostingEnvironment env, ConsoleArgs args)
{
...
So in case of your controller class do the same: 因此,如果你的控制器类做同样的事情:
public class YourController : Controller
{
public YourController(ConsoleArgs args)
{
//use args here or store it in private variable
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.