1、配置代码
配置方法有两种,具体如下,
1)代码中配置
var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(5001); // 端口 options.ListenAnyIP(7001, configure => configure.UseHttps()); // https 端口 }); var app = builder.Build();
2)使用appsettings.json 配置
appsettings.json :
{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5000" } } } }
Program.cs:
builder.Configuration.SetBasePath(app.Environment.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{app.Environment.EnvironmentName}.json", optional: true) .AddEnvironmentVariables();
2、项目中完整代码
Program.cs 文件内容如下:
using Microsoft.OpenApi.Models; using NLog.Web; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Logging.ClearProviders(); builder.Host.UseNLog(); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(5001); // 端口 options.ListenAnyIP(7001, configure => configure.UseHttps()); // https 端口 }); var app = builder.Build(); ServiceLocator.Instance = app.Services; //获取 appsettings.json 中配置 var config = app.Configuration; var smtpServer = config["settings:SmtpServer"]; //app.UseAuthentication(); //app.UseAuthorization(); app.UseDefaultFiles(); app.UseStaticFiles(); app.MapControllers();
未使用 IIS 托管时,ASP.NET Core 项目模板默认使用 Kestrel。 在下面的模板生成的 Program.cs 中,WebApplication.CreateBuilder 方法在内部调用 UseKestrel()
。