xxyy
2025-03-10 ffe8ac13ba8bc9426f8b5f5b88f094a05b31b7ff
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Concurrent;
using System.Text.Json;
 
public class ThrottleFilter : IAsyncActionFilter
{
    private static readonly ConcurrentDictionary<string, DateTime> _lastExecutionTimes = new ConcurrentDictionary<string, DateTime>();
    private readonly int _intervalInSeconds;
 
    public ThrottleFilter(int intervalInSeconds)
    {
        _intervalInSeconds = intervalInSeconds;
    }
 
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var actionName = context.ActionDescriptor.DisplayName;
 
        var parameterString = GenerateParameterString(context.ActionArguments);
        var key = $"{actionName}_{parameterString}";
 
        if (_lastExecutionTimes.TryGetValue(key, out var lastExecutionTime))
        {
            var elapsedTime = DateTime.Now - lastExecutionTime;
            if (elapsedTime.TotalSeconds < _intervalInSeconds)
            {
                context.Result = new OkObjectResult(new WebResponseContent().Error("请求过于频繁,请稍后再试"));
                return;
            }
        }
 
        _lastExecutionTimes[key] = DateTime.Now;
        await next();
    }
 
    private string GenerateParameterString(IDictionary<string, object> arguments)
    {
        if (arguments == null || arguments.Count == 0)
        {
            return "";
        }
 
        var paramStrings = new List<string>();
        foreach (var argument in arguments)
        {
            var key = argument.Key;
            var value = argument.Value;
            string valueString;
 
            if (value == null)
            {
                valueString = "null";
            }
            else if (IsSimpleType(value.GetType()))
            {
                valueString = value.ToString();
            }
            else
            {
                valueString = JsonSerializer.Serialize(value);
            }
 
            paramStrings.Add($"{key}={valueString}");
        }
 
        return string.Join("&", paramStrings);
    }
 
    // 判断类型是否为简单类型
    private bool IsSimpleType(Type type)
    {
        return type.IsPrimitive || type == typeof(string) || type == typeof(decimal);
    }
}