67 lines
1.8 KiB
C#
67 lines
1.8 KiB
C#
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;
|
|
}
|
|
}
|
|
} |