解决.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 存储请求信息,能处理分布式环境下的请求频率限制。
相关推荐
追逐时光者7 小时前
一个基于 .NET 开源、功能强大的分布式微服务开发框架
后端·.net
笺上知微7 小时前
Serilog基于Seq开源框架实现日志分析
.net
百锦再7 小时前
Vue Scoped样式混淆问题详解与解决方案
java·前端·javascript·数据库·vue.js·学习·.net
CodeCraft Studio8 小时前
【能源与流程工业案例】KBC借助TeeChart 打造工业级数据可视化平台
java·信息可视化·.net·能源·teechart·工业可视化·工业图表
一个帅气昵称啊9 小时前
使用微软Agent Framework .NET构建智能代理应用
microsoft·flask·.net
一个天蝎座 白勺 程序猿10 小时前
深度解析:通过ADO.NET驱动Kdbndp高效连接与操作Kingbase数据库
数据库·.net·wpf·kingbase·金仓数据库
时光追逐者11 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图
我是唐青枫11 小时前
C#.NET FluentValidation 全面解析:优雅实现对象验证
c#·.net
VB.Net12 小时前
VB.Net循序渐进(第二版)
开发语言·.net·vb.net