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)代码中配置

1
2
3
4
5
6
7
8
9
10
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 :

1
2
3
4
5
6
7
8
9
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:5000"
      }
    }
  }
}

  Program.cs:

1
2
3
4
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 文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 @   yinghualeihenmei  阅读(152)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-07-01 给三十几万条数据加序号(sqlserver与excel)
2022-07-01 .csv文件与excel文件的区别
2022-07-01 人脸数据库的特征提取
点击右上角即可分享
微信分享提示