.Net Core 修改默认的启动端口

    今天无意中发现一个变化,因为很久没看.net core的项目了,发现项目启动的默认端口已经不是5000了,记得很清楚,最早那还是.net core 1.x版本的时候,每次启动都会默认是5000端口号,而现在不是了。借此机会在来说一下,关于.net core项目修改默认端口号的解决方案,我们最熟知的是一种解决方案就是直接在Program.cs中创建WebHost对象的时候,使用UseUrls()方法,配置要使用的端口,如下所示:

这是我们再熟悉不过的修改方法了,启动以后,5001和5002端口都会开启监听,所以我们通过这两个地址都会访问到我们的网站。但是这种方式的缺点就是我们要修改代码,重新编译运行,这并不是我们想要的最好的解决方案,如果可以直接在配置文件中配置就完美了,便在一个个人博客里看到了一个方法,地址:http://benfoster.io/blog/how-to-configure-kestrel-urls-in-aspnet-core-rc2 添加一个json文件,叫做hosting.json,意为服务配置,当然起什么名字不重要,里面只需要添加一个节点即可,内容如下:

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

添加了一个server.urls节点,然后再修改Program.cs文件,

运行后,显示如下:

5001和5002端口都开启了监听。

这不禁引起了我的兴趣,便翻起了关于这一块儿的源码。关于Hosting的源码地址:https://github.com/aspnet/Hosting

下面我们层层深入,究其原因,查看IWebHost接口的Build方法:


    
    
  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. }
在Build方法里主要是初始化了一个WebHost对象,再进入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. }

不难找到是在上述方法里面,添加的URL地址,在这行代码中:

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

W这里的URL判断,如果当前默认的配置为空则使用后面的配置,而DepreacatedServerUrlsKey在一开始就已经定义了,

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

该参数的默认值为server.urls,所以我们在hosting.json中直接配置该键值对,.net core启动后会自动读取配置文件,使用配置的端口。细心的小伙伴会发现在源代码中,还有两处是关于配置Url的,一处是在上面的Build方法中,有一处判断:


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

如果在环境变量中ASPNETCORE_SERVER.URLS不为空的话,这个值就会替换ASPNETCORE_URLS的值,另外在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. }

如果获取的默认的配置中urls的值为空,那么就启用ASPNETCORE_SERVER.URLS环境变量中的配置,这也告诉我们我们还可以把启动的端口放到环境变量中,右键项目属性,选择调试,

添加环境变量ASPNETCORE_SERVER.URLS配置,以上就是我总结的修改默认启动端口的所有方法了,如果还有其他的方法,欢迎留言。

晚安。


扫描二维码关注我的公众号,共同学习,共同进步!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值