. Net Core modifies the default boot port

Keywords: C# .NET microsoft

     Today, I accidentally found a change because I haven't seen the. net core project for a long time. I found that the default port for project startup is not 5000. I remember clearly that when it was version 1. X of. net core, the default port number for each startup was 5000, but not now. Take this opportunity to talk about the solution to modify the default port number of the. net core project. The most familiar solution is to use the UseUrls() method to configure the port to be used when directly creating the WebHost object in Program.cs, as shown below:

This is the most familiar modification method. After startup, ports 5001 and 5002 will start listening, so we will visit our website through these two addresses. However, the disadvantage of this method is that we need to modify the code and recompile it for operation. This is not the best solution we want. If it can be configured directly in the configuration file, it is perfect. I saw a method in a personal blog, address: http://benfoster.io/blog/how-to-configure-kestrel-urls-in-aspnet-core-rc2   Add a JSON file called hosting.json, which means service configuration. Of course, the name doesn't matter. Only one node needs to be added. The contents are as follows:

<span style="font-size:14px;">{
  "server.urls": "http://localhost:5001;http://localhost:5002"
}</span>

Add a server.urls node, and then modify the Program.cs file,

After operation, the display is as follows:

Both ports 5001 and 5002 have listening enabled.

This aroused my interest and turned to the source code about this piece. About the source code address of Hosting: https://github.com/aspnet/Hosting

Next, let's go deep into the reasons and check the Build method of IWebHost interface:

    
  1. /// <summary>
  2. /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application.
  3. /// </summary>
  4. public IWebHost Build()
  5. {
  6. if (_webHostBuilt)
  7. {
  8. throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance);
  9. }
  10. _webHostBuilt = true;
  11. var hostingServices = BuildCommonServices( out var hostingStartupErrors);
  12. var applicationServices = hostingServices.Clone();
  13. var hostingServiceProvider = GetProviderFromFactory(hostingServices);
  14. if (!_options.SuppressStatusMessages)
  15. {
  16. // Warn about deprecated environment variables
  17. if (Environment.GetEnvironmentVariable( "Hosting:Environment") != null)
  18. {
  19. Console.WriteLine( "The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
  20. }
  21. if (Environment.GetEnvironmentVariable( "ASPNET_ENV") != null)
  22. {
  23. Console.WriteLine( "The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'");
  24. }
  25. if (Environment.GetEnvironmentVariable( "ASPNETCORE_SERVER.URLS") != null)
  26. {
  27. Console.WriteLine( "The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'");
  28. }
  29. }
  30. var logger = hostingServiceProvider.GetRequiredService<ILogger<WebHost>>();
  31. // Warn about duplicate HostingStartupAssemblies
  32. foreach ( var assemblyName in _options.GetFinalHostingStartupAssemblies().GroupBy(a => a, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1))
  33. {
  34. logger.LogWarning( $"The assembly {assemblyName} was specified multiple times. Hosting startup assemblies should only be specified once.");
  35. }
  36. AddApplicationServices(applicationServices, hostingServiceProvider);
  37. var host = new WebHost(
  38. applicationServices,
  39. hostingServiceProvider,
  40. _options,
  41. _config,
  42. hostingStartupErrors);
  43. try
  44. {
  45. host.Initialize();
  46. return host;
  47. }
  48. catch
  49. {
  50. // Dispose the host if there's a failure to initialize, this should clean up
  51. // will dispose services that were constructed until the exception was thrown
  52. host.Dispose();
  53. throw;
  54. }
The Build method mainly initializes a WebHost object, and then enters the source code of WebHost,
    
  1. private void EnsureServer()
  2. {
  3. if (Server == null)
  4. {
  5. Server = _applicationServices.GetRequiredService<IServer>();
  6. var serverAddressesFeature = Server.Features?.Get<IServerAddressesFeature>();
  7. var addresses = serverAddressesFeature?.Addresses;
  8. if (addresses != null && !addresses.IsReadOnly && addresses.Count == 0)
  9. {
  10. var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];
  11. if (! string.IsNullOrEmpty(urls))
  12. {
  13. serverAddressesFeature.PreferHostingUrls = WebHostUtilities.ParseBool(_config, WebHostDefaults.PreferHostingUrlsKey);
  14. foreach ( var value in urls.Split( new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
  15. {
  16. addresses.Add( value);
  17. }
  18. }
  19. }
  20. }
  21. }

It is not difficult to find the URL address added in the above method. In this line of code:

var urls = _config[WebHostDefaults.ServerUrlsKey] ?? _config[DeprecatedServerUrlsKey];
    

W according to the URL judgment here, if the current default configuration is empty, the following configuration will be used, and the deprecated serverurlskey has been defined at the beginning,

private static readonly string DeprecatedServerUrlsKey = "server.urls";
    

The default value of this parameter is server.urls, so we directly configure this key value pair in hosting.json. After. net core starts, it will automatically read the configuration file and use the configured port. Careful partners will find that in the source code, there are two other points about configuring URLs. One is in the Build method above, and there is one judgment:

    
  1. if (Environment.GetEnvironmentVariable( "ASPNETCORE_SERVER.URLS") != null)
  2. {
  3. Console.WriteLine( "The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'");
  4. }

If aspnetcore is in the environment variable_ If server.urls is not empty, this value will replace aspnetcore_ In addition, there is a judgment code in the constructor of WebHostBuilder

    
  1. if ( string.IsNullOrEmpty(GetSetting(WebHostDefaults.ServerUrlsKey)))
  2. {
  3. // Try adding legacy url key, never remove this.
  4. UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable( "ASPNETCORE_SERVER.URLS"));
  5. }

If the value of URLs in the obtained default configuration is null, aspnetcore is enabled_ The configuration in the server.urls environment variable also tells us that we can also put the startup port into the environment variable, right-click the project attribute and select debug,

Add environment variable ASPNETCORE_SERVER.URLS configuration. The above is all the methods I summarized to modify the default startup port. If there are other methods, please leave a message.

good night.


Scan the two-dimensional code, pay attention to my official account, learn together and make progress together!

Posted by comicrage on Thu, 28 Oct 2021 05:03:18 -0700