解决.net接口防暴力调用问题

在 .NET 中,为解决接口防暴力调用问题,可通过限制请求频率实现。下面给出几种不同实现方式。

基于内存的简单速率限制

此方法适用于单服务器环境,它借助内存字典来记录每个客户端的请求次数和时间。

MemoryRateLimitMiddleware.cs

复制代码
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class MemoryRateLimitMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ConcurrentDictionary<string, (int Count, DateTime LastRequestTime)> _requestCounts = new ConcurrentDictionary<string, (int Count, DateTime LastRequestTime)>();
    private readonly int _maxRequests;
    private readonly TimeSpan _timeWindow;

    public MemoryRateLimitMiddleware(RequestDelegate next, int maxRequests, TimeSpan timeWindow)
    {
        _next = next;
        _maxRequests = maxRequests;
        _timeWindow = timeWindow;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var clientIp = context.Connection.RemoteIpAddress.ToString();
        var now = DateTime.UtcNow;

        if (_requestCounts.TryGetValue(clientIp, out var entry))
        {
            if (now - entry.LastRequestTime < _timeWindow)
            {
                if (entry.Count >= _maxRequests)
                {
                    context.Response.StatusCode = 429;
                    await context.Response.WriteAsync("请求频率过高,请稍后再试。");
                    return;
                }
                _requestCounts[clientIp] = (entry.Count + 1, entry.LastRequestTime);
            }
            else
            {
                _requestCounts[clientIp] = (1, now);
            }
        }
        else
        {
            _requestCounts.TryAdd(clientIp, (1, now));
        }

        await _next(context);
    }
}

Startup.cs

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseMiddleware<MemoryRateLimitMiddleware>(100, TimeSpan.FromMinutes(1));

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

基于 Redis 的分布式速率限制

若应用部署在分布式环境,可使用 Redis 存储请求信息。需安装 StackExchange.Redis 包。

RedisRateLimitMiddleware.cs

复制代码
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using StackExchange.Redis;

public class RedisRateLimitMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IDatabase _redisDb;
    private readonly int _maxRequests;
    private readonly TimeSpan _timeWindow;

    public RedisRateLimitMiddleware(RequestDelegate next, ConnectionMultiplexer redis, int maxRequests, TimeSpan timeWindow)
    {
        _next = next;
        _redisDb = redis.GetDatabase();
        _maxRequests = maxRequests;
        _timeWindow = timeWindow;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var clientIp = context.Connection.RemoteIpAddress.ToString();
        var key = $"request_count:{clientIp}";

        var count = await _redisDb.StringGetAsync(key);
        if (count.HasValue)
        {
            var currentCount = int.Parse(count);
            if (currentCount >= _maxRequests)
            {
                context.Response.StatusCode = 429;
                await context.Response.WriteAsync("请求频率过高,请稍后再试。");
                return;
            }
            await _redisDb.StringIncrementAsync(key);
        }
        else
        {
            await _redisDb.StringSetAsync(key, 1, _timeWindow);
        }

        await _next(context);
    }
}

StartupRedis.cs

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;

public class StartupRedis
{
    public void ConfigureServices(IServiceCollection services)
    {
        var redis = ConnectionMultiplexer.Connect("localhost");
        services.AddSingleton<IConnectionMultiplexer>(redis);
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConnectionMultiplexer redis)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseMiddleware<RedisRateLimitMiddleware>(redis, 100, TimeSpan.FromMinutes(1));

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

解释

  • 基于内存的简单速率限制 :借助 ConcurrentDictionary 记录每个客户端的请求次数和时间,当请求频率超出限制时,返回 429 状态码。
  • 基于 Redis 的分布式速率限制:使用 Redis 存储请求信息,能处理分布式环境下的请求频率限制。
相关推荐
weixin_464078074 小时前
.NET 多线程题目汇总
算法·.net
ChaITSimpleLove2 天前
快速体验 .NET9 提供的 HybridCache 混合缓存
redis·.net·分布式缓存·本地缓存·混合缓存·garnet 分布式缓存·hybridcache
XiaoyuEr_66882 天前
.NET 平台详解
.net
时光追逐者2 天前
一款基于 .NET 开源的多功能的 B 站视频下载工具
c#·.net·音视频
o0向阳而生0o2 天前
36、C#中的⽅法声明参数关键字params,ref,out的意义及⽤法
开发语言·c#·.net
TeamDev3 天前
DotNetBrowser 3.2.0 版本发布啦!
.net·dotnet·chromium·winforms·dotnetbrowser·avalonia ui·user agent
码观天工3 天前
.NET 原生驾驭 AI 新基建实战系列(六):Pinecone ── 托管向量数据库的向量数据库的云原生先锋
ai·c#·.net·pinecone·向量数据库
江沉晚呤时3 天前
深入解析 .NET Kestrel:高性能 Web 服务器的架构与最佳实践
服务器·前端·.net
o0向阳而生0o3 天前
35、C# 中的反射(Reflection)
开发语言·c#·.net
江沉晚呤时3 天前
深入了解 OpenIddict:实现 OAuth 2.0 和 OpenID Connect 协议的 .NET 库
后端·c#·.net·.net core