Adding RateLimit Feature ...

This commit is contained in:
2026-11-09 15:40:10 +03:30
parent 0a8f9692dd
commit cba7637255
17 changed files with 787 additions and 10 deletions
+67
View File
@@ -0,0 +1,67 @@
using System.Linq;
using xCommons.Configurations;
namespace xCommons.Extensions
{
public static class XCommonsExtensions
{
/// <summary>
/// Extract RateLimit Rule based on given Path ...
/// </summary>
/// <param name="source"></param>
/// <param name="path"></param>
/// <returns></returns>
public static XRateLimitRule GetMatchingRule(
this XRateLimitConfiguration source,
string path
)
{
//
if (!source.Enabled)
{
return null;
}
//
var normalizedPath = path.IsNullOrEmpty()
? "/"
: path.ToNormalString();
//
var rule = source.Rules.IsNull()
? null
: source.Rules
.Where(r =>
!r.IsNull() &&
r.Enabled &&
!r.PathPrefix.IsNullOrEmpty() &&
normalizedPath.StartsWith(r.PathPrefix.ToNormalString()))
.OrderByDescending(r => r.PathPrefix.Length)
.FirstOrDefault();
//
if (!rule.IsNull())
{
return rule;
}
//
if (source.ApplyToAllRoutes)
{
//
return new XRateLimitRule
{
Enabled = true,
Name = "Default",
PathPrefix = "/",
Limit = source.DefaultLimit,
KeyMode = source.DefaultKeyMode,
PeriodSeconds = source.DefaultPeriodSeconds,
};
}
//
return null;
}
}
}