2025澳门开彩结果历史记录-2025澳门开彩结果-2025澳门开彩查询记录-2025澳门聚宝盆-2025澳门九点半一肖一码-2025澳门精准资料免费全览

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

如何在 ASP.NET Core 中實現(xiàn)速率限制?

freeflydom
2025年1月16日 11:2 本文熱度 388

在 ASP.NET Core 中實現(xiàn)速率限制(Rate Limiting)中間件可以幫助你控制客戶端對 API 的請求頻率,防止濫用和過載。速率限制通常用于保護服務(wù)器資源,確保服務(wù)的穩(wěn)定性和可用性。

ASP.NET Core 本身并沒有內(nèi)置的速率限制中間件,但你可以通過自定義中間件或使用第三方庫來實現(xiàn)速率限制。以下是實現(xiàn)速率限制的幾種常見方法:


1. 使用自定義中間件實現(xiàn)速率限制

你可以通過自定義中間件來實現(xiàn)速率限制。以下是一個簡單的實現(xiàn)示例:

1.1 實現(xiàn)速率限制中間件

using Microsoft.AspNetCore.Http;
using System.Collections.Concurrent;
using System.Threading.Tasks;
public class RateLimitingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly int _maxRequests; // 每分鐘允許的最大請求數(shù)
    private readonly ConcurrentDictionary<string, RateLimiter> _rateLimiters;
    public RateLimitingMiddleware(RequestDelegate next, int maxRequests)
    {
        _next = next;
        _maxRequests = maxRequests;
        _rateLimiters = new ConcurrentDictionary<string, RateLimiter>();
    }
    public async Task InvokeAsync(HttpContext context)
    {
        // 獲取客戶端的唯一標(biāo)識(例如 IP 地址)
        var clientId = context.Connection.RemoteIpAddress.ToString();
        // 獲取或創(chuàng)建速率限制器
        var rateLimiter = _rateLimiters.GetOrAdd(clientId, _ => new RateLimiter(_maxRequests));
        if (rateLimiter.AllowRequest())
        {
            await _next(context);
        }
        else
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
            await context.Response.WriteAsync("請求太多。請稍后再試.");
        }
    }
}
public class RateLimiter
{
    private readonly int _maxRequests;
    private int _requestCount;
    private DateTime _windowStart;
    public RateLimiter(int maxRequests)
    {
        _maxRequests = maxRequests;
        _requestCount = 0;
        _windowStart = DateTime.UtcNow;
    }
    public bool AllowRequest()
    {
        var now = DateTime.UtcNow;
        // 如果當(dāng)前時間窗口已過期,重置計數(shù)器
        if ((now - _windowStart).TotalSeconds > 60)
        {
            _requestCount = 0;
            _windowStart = now;
        }
        // 檢查請求是否超出限制
        if (_requestCount < _maxRequests)
        {
            _requestCount++;
            return true;
        }
        return false;
    }
}

1.2 注冊中間件

在 Startup.cs 中注冊中間件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<RateLimitingMiddleware>(10); // 每分鐘最多 10個請求
    app.UseRouting();
    app.UseEndpoints(endpoints =>
                     {
                         endpoints.MapControllers();
                     });
}

2. 使用第三方庫實現(xiàn)速率限制

如果你不想自己實現(xiàn)速率限制邏輯,可以使用一些現(xiàn)成的第三方庫,例如:

2.1 AspNetCoreRateLimit

AspNetCoreRateLimit 是一個流行的 ASP.NET Core 速率限制庫,支持 IP 地址、客戶端 ID 和端點級別的速率限制。

安裝

通過 NuGet 安裝:

dotnet add package AspNetCoreRateLimit
配置

在 Startup.cs 中配置速率限制:

public void ConfigureServices(IServiceCollection services)
{
    // 添加內(nèi)存緩存
    services.AddMemoryCache();
    // 配置速率限制
    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
    services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
    services.AddInMemoryRateLimiting();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseIpRateLimiting();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
                     {
                         endpoints.MapControllers();
                     });
}
配置文件

在 appsettings.json 中添加速率限制配置:

{
    "IpRateLimiting": {
        "EnableEndpointRateLimiting": true,
        "StackBlockedRequests": false,
        "RealIpHeader": "X-Real-IP",
        "ClientIdHeader": "X-ClientId",
        "GeneralRules": [
            {
                "Endpoint": "*",
                "Period": "1m",
                "Limit": 10
                }
        ]
    }
}

3. 使用分布式緩存實現(xiàn)速率限制

如果你的應(yīng)用是分布式的(例如部署在 Kubernetes 或多個服務(wù)器上),可以使用分布式緩存(如 Redis)來實現(xiàn)速率限制。

3.1 使用 Redis 實現(xiàn)速率限制

你可以使用 Redis 來存儲每個客戶端的請求計數(shù)。以下是一個簡單的示例:

using Microsoft.AspNetCore.Http;
using StackExchange.Redis;
using System.Threading.Tasks;
public class RedisRateLimitingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly int _maxRequests;
    private readonly ConnectionMultiplexer _redis;
    public RedisRateLimitingMiddleware(RequestDelegate next, int maxRequests, ConnectionMultiplexer redis)
    {
        _next = next;
        _maxRequests = maxRequests;
        _redis = redis;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        var clientId = context.Connection.RemoteIpAddress.ToString();
        var db = _redis.GetDatabase();
        var key = $"rate_limit:{clientId}";
        var requestCount = await db.StringIncrementAsync(key);
        if (requestCount == 1)
        {
            await db.KeyExpireAsync(key, TimeSpan.FromMinutes(1));
        }
        if (requestCount > _maxRequests)
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
            await context.Response.WriteAsync("請求太多。請稍后再試.");
        }
        else
        {
            await _next(context);
        }
    }
}

3.2 注冊中間件

在 Startup.cs 中注冊中間件:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost:6379"));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<RedisRateLimitingMiddleware>(10); // 每分鐘最多 10個請求
    app.UseRouting();
    app.UseEndpoints(endpoints =>
                     {
                         endpoints.MapControllers();
                     });
}

4. 總結(jié)

在 ASP.NET Core 中實現(xiàn)速率限制有多種方式:

  • 自定義中間件:適合簡單的場景,但需要自己實現(xiàn)邏輯。
  • 第三方庫:如 AspNetCoreRateLimit,提供了更強大的功能和靈活性。
  • 分布式緩存:如 Redis,適合分布式環(huán)境。

根據(jù)你的需求選擇合適的方式,確保你的 API 能夠有效防止濫用和過載。

?轉(zhuǎn)自https://www.cnblogs.com/liyongqiang-cc/p/18628407


該文章在 2025/1/16 11:02:11 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調(diào)度、堆場、車隊、財務(wù)費用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點,圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務(wù)都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 平码3中3免费网站 | 澳门与香港一肖一码100%精准的背景故事 | 2025年澳门资料大全 | 澳门四不像图片大全 | 六盒宝典资料免费大全下 | 7个号码三期必出一期最新内部资料下载 | 2025年正版资料免费大全功能介绍 | 澳门今晚一肖码10o准管家娶 | 2025澳门精准正版免费大全 | 118图库彩图118开奖软件v | 重庆市主要领导调整 | 新澳门内部资料精准大全 | 澳彩精准快全篇资 | 一码一肖100准吗 | 澳门九龙资料免费公开资料新手 | 王中王一肖一特一中免费 | 澳门一肖一码必中一肖一码 | 2025澳门正版资料大全 | 澳门最准一肖一码一码配套成龙A | 494949CC兔费资料大全 | 三五图库大全免费印刷 | 2025澳门精准正版资料大全 | 澳门彩资料大全集(中国)官方网站ios | 澳门1肖一码100准on | 最准一肖一码一一中一特正版全年免费资料 | 澳门天天彩免费正版 | 2025澳门准一肖一码一码 | 澳门权威免费资料大全一览 | 澳门最准最快资料 | 澳门资料大全正版资料192 | 今晚双色球精准预测一注 | 今晚开什么2025年 | 2025澳门正版资料全 | 三五图库网通jpg印刷区 | 7777888888精准管家婆香港 | 管家婆通用官网 | 2025澳门传真澳门传 | 今晚特马号2025年 | 摇钱树免费公开资料一肖中特 | 今晚澳门开什么特到 | 今晚澳门必中一肖 |