在ASP.NET Core开发中默认端口的修改是一个常见的需求。无论是为了与其他应用程序避免端口冲突还是在开发环境中方便测试修改默认端口都是一个基础而重要的操作。本文将介绍五种常用的方法来修改ASP.NET Core的默认端口并提供相应的例子代码。方法一通过appsettings.json配置Kestrel的EndpointASP.NET Core使用Kestrel作为默认的Web服务器你可以在appsettings.json文件中配置Kestrel的Endpoint来修改默认端口。示例代码在appsettings.json文件中添加Kestrel配置{ Kestrel: { Endpoints: { Http: { Url: http://localhost:5001 }, Https: { Url: https://localhost:5002 } } } }在Startup.cs文件中读取配置并使用Kestrel Endpointpublic classStartup { privatereadonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration configuration; } public void ConfigureServices(IServiceCollection services) { // 添加服务配置 } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 其他中间件配置 var url _configuration[Kestrel:Endpoints:Http:Url]; // 这里只是示例实际中Kestrel的Endpoint配置不需要额外代码来读取和设置 app.Run(async (context) { await context.Response.WriteAsync($Hello from {url}!); }); } }注意在ASP.NET Core 3.x及以后版本中通常不需要在Startup.cs中显式读取并使用Kestrel的配置因为Kestrel会自动从appsettings.json读取配置。方法二使用UseUrls方法在Program.cs文件中你可以使用UseUrls方法来指定应用程序的URL和端口。示例代码public classProgram { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder { webBuilder.UseUrls(http://localhost:5001, https://localhost:5002); // 在这里指定端口号 webBuilder.UseStartupStartup(); }); }方法三通过命令行参数指定端口在启动应用程序时你可以通过命令行参数来指定端口。示例命令dotnet run --urls http://localhost:5001方法四使用launchSettings.json文件开发环境如果你只想在开发环境中更改端口可以修改launchSettings.json文件。示例代码在Properties文件夹下的launchSettings.json文件中找到与你的应用程序配置对应的部分并修改applicationUrl字段{ profiles: { IIS Express: { commandName: IISExpress, launchBrowser: true, environmentVariables: { ASPNETCORE_ENVIRONMENT: Development }, iisSettings: { windowsAuthentication: false, anonymousAuthentication: true, iisExpress: { applicationUrl: http://localhost:5001, sslPort: 0 } } }, YourProjectName: { commandName: Project, launchBrowser: true, applicationUrl: http://localhost:5001, environmentVariables: { ASPNETCORE_ENVIRONMENT: Development } } } }方法五使用环境变量你可以通过设置环境变量来设置ASP.NET Core应用程序的默认URL和端口。示例命令在Windows上$env:ASPNETCORE_URLShttp://localhost:5001 dotnet run在Linux或macOS上export ASPNETCORE_URLShttp://localhost:5001 dotnet run总结通过上述五种方法你可以根据不同的项目需求和环境设置灵活地修改ASP.NET Core应用程序的默认端口。在开发环境中推荐使用launchSettings.json或命令行参数来方便测试在生产环境中推荐使用appsettings.json或环境变量来设置固定的端口以确保应用程序的稳定性和安全性。选择适合你的项目的方法并根据需要进行相应的配置和代码调整。