2021年7月31日 星期六

[ASP.NET Core] Run the same project at local by different port and environment variable

 ASP.NET Core   Development  

 

Introduction


 

Sometimes we want to run the same project at local as two or more processes that each of them has different port and environment variable.

 

The best way is to containerize your application.

However, if you want a quick solution in order to do some simple tests in this scenario, we can use dotnet CLI and a few setups to achieve it.   

 

Environment


 .NET Core 5.0.301

Visual  Studio 2019 Community

 

 

 

Implement



Here are 2 tips of dotnet CLI to run a project as multiple processes with different port and environment variable.

 

1.Launch profiles


The launchSettings.json file describes how the application launches by specified URL, port, environment variables, etc.

 

We can define multiple launch profile in that file. For example, we have 2 launch profiles in the following launchSettings.json, "Demo.Client1" and "Demo.Client2".

{
  "$schema""http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "Demo.Client1": {
      "commandName""Project",
      "launchBrowser"true,
      "launchUrl""Home",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT""Client1"
      },
      "dotnetRunMessages""true",
      "applicationUrl""https://localhost:5001;http://localhost:5000"
    },
    "Demo.Client2": {
      "commandName""Project",
      "launchBrowser"true,
      "launchUrl""Home",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT""Client2"
      },
      "dotnetRunMessages""true",
      "applicationUrl""https://localhost:5003;http://localhost:5002"
    }
  }
}

 

Now we can switch different launch profile when execute "dotnet run".

 

$ dotnet run --launch-profile Demo.Client1

 

 

Notice that the above command will BUILD THE PROJECT and put the built binaries to "/bin/Debug/". If we modify the code and run another "dotnet run –launch-profile Demo.Client2", it will cause the following error:

 

 

The process cannot access the file '…\src\Demo.Client\bin\Debug\net5.0\Demo.Client.exe' because it is being used by another process.  […\src\Demo.Client\Demo.Client.csproj]

 

 

 

We can specified the "--configuration|-c" argument to build and put the binaries in different path.

 

For example, it is safe to run 2 processes like this:

 

$ dotnet run --configuration client1 --launch-profile Demo.Client1
$ dotnet run --configuration client2 --launch-profile Demo.Client2

 

 

And the binaries will be put at "bin\client1" and "bin\client2".

 

$ ls Demo.Client\bin\
client1/  client2/

 

 

 

 

 

2.Passing program arguments

 

The other tip to use the program arguments.

Since we can set the Kestrel web-server’s options by config file or by WebHostBuilderKestrelExtensions.ConfigureKestrel Method (See Configure options for the ASP.NET Core Kestrel web server), we can take the program arguments and then set the custom configuration for each process.

 

For example, I want to run the same project in 2 processes with different port and different values of environment variable "ASPNETCORE_ENVIRONMENT".

 

$ cd Demo.Client\bin\Debug\net5.0
$ dotnet Demo.Client.dll --urls https://localhost:5001 --env Client1
$ dotnet Demo.Client.dll --urls https://localhost:5003 --env Client2

 

  

The "--urls" is a default argument of "dotnet run" that will set the listening URL of Kestrel webserver. "--env" is the custom argument that we will catch and update the "ASPNETCORE_ENVIRONMENT" value in our application.

public class Program
{
        public static void Main(string[] args)
        {
            if (args is { Length: > 0 })
            {
                #region Set the ASPNETCORE_ENVIRONMENT variable to the process by argument

                const string targetArg = "--env[= ]";
                var reg = new Regex($"{targetArg}.*");
                string env = args.Where(arg => reg.IsMatch(arg)).Take(1) .Select(s => Regex.Replace(stargetArg"")) .FirstOrDefault();
                Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"env);
                #endregion
            }

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        // Set properties and call methods on options
                    }).UseStartup<Startup>();
                });
}


 

Reference


 

Configure options for the ASP.NET Core Kestrel web server

 

 


沒有留言:

張貼留言