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();