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

原文链接:https://blog.csdn.net/weixin_52026996/article/details/135929070

简介:
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();

  未使用 IIS 托管时,ASP.NET Core 项目模板默认使用 Kestrel。 在下面的模板生成的 Program.cs 中,WebApplication.CreateBuilder 方法在内部调用 UseKestrel()。

posted @ 2024-07-01 16:23  yinghualeihenmei  阅读(5)  评论(0编辑  收藏  举报