我建了一个简单的 .NET 6 WebAPI项目,其中Program.cs是这样的:
using AspNetCoreRateLimit;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// IpRateLimit
//需要从加载配置文件appsettings.json
builder.Services.AddOptions();
//需要存储速率限制计算器和ip规则
builder.Services.AddMemoryCache();
//从appsettings.json中加载常规配置
builder.Services.Configure<ClientRateLimitOptions>(Configuration.GetSection("IPRateLimiting"));
//从appsettings.json中加载客户端规则
builder.Services.Configure<ClientRateLimitPolicies>(Configuration.GetSection("ClientRateLimitPolicies"));
//注入计数器和规则存储
builder.Services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
//end of IpLimit
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
但是其中的Configuration.GetSection()编译通不过,我也不知道应该引入哪一个命名空间?
引用 Microsoft.Extensions.Configuration
还是这样
@泰德: builder.Configuration.GetSection("IPRateLimiting")
@dudu:
谢谢!
看了好多搜索结果,也没有找到这个,不明白这种最基础的东西为什么没有资料。
@泰德: 这种 Program 新写法是 .NET 6.0 新引入的