ASP.NET Core 6 (.NET 6) 配置使用kestrel server

Kestrel 是一个跨平台的、开源的、轻量级的 HTTP 服务器,它是 ASP.NET Core 的默认 Web 服务器。Kestrel 是跨平台的,因此可以在不同的操作系统上运行,包括 Windows、Linux 和 macOS。本文主要介绍ASP.NET Core 6中kestrel 的配置及使用。

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

推荐阅读
cjavapy编程之路首页