简体   繁体   中英

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.

  • This blog explained a lot of useful setup, but not how to actually use custom arguments other than --environment .
  • I've found ways to pass command line arguments into the Startup class , but not how to get it into the controller.
  • Upon looking at the docs , I cannot correctly pass the parameters to controller classes (the sample file also conflates the Program and Startup classes, so I am not sure how to handle that in my own code).

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.

I've found ways to pass command line arguments into the Startup class , but not how to get it into the controller.

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. Then it could be used as the dependency in any class. Like into Startup class in linked example:

// 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM