The lightweight .NET package provides a middleware service to protect your application by limiting the request rate. Suport old .NET Framework Project, support Redis, MemoryCache, System.Web.Caching.Cache.
$ dotnet add package RateLimit.FrameworkRateLimit.Framworklightweight package provides a middleware service to protect your application by limiting the request rate.old .NET Framework projectRedis, MemoryCache, System.Web.Caching.CacheIpAddress (can be config using with CookieName) contains the number of requests which cross over the MaxRequestPerPeriod, it will be blocked by returning a TooManyRequest(429) (config by BlockMessage) within the blocking time (config by BlockTimeSecond)ExampleController.cs: config RateLimitAttribute for GetReport actionusing Newtonsoft.Json;
using System.Web.Mvc;
using RateLimit; // use RateLimit package
namespace WebMVC.Controllers
{
public class ExampleController : Controller
{
/* Config for every request come to this action */
[RateLimit(PeriodTime = 10, MaxRequestPerPeriod = 1, BlockTime = 10, BlockMessage = "You are making too many request")]
public string GetReport(string param1)
{
return param1;
}
}
}
Global.asax.cs: custom regis global RateLimit configuration/// ...
using RateLimit; // use RateLimit package
using RateLimit.Configs; // use RateLimit package configuration
namespace WebMVC
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
/// ...
/// ...
/* Full global config */
RateLimitContext.RegisterConfig(
new RateLimitConfig(
/* Global config for request rate */
rateConfig: new RequestRateConfig
{
BlockMessage = "You are making too many request, please try after 60 second",
BlockTime = 60,
CookieName = "ASP.NET_SessionId",
MaxRequestPerPeriod = 1,
PeriodTime = 10
},
/* Cache config, default is new HttpRuntimeConfig() */
cacheConfig: new RedisConfig()
{
CacheTimeSecond = 3600,
ConnectTimeoutSecond = 5,
DatabaseIndex = 0,
EndPoints = "localhost:6379"
}
)
);
}
}
}
ExampleController.cs: Use default global rate configuration/// ...
using RateLimit; // use RateLimit package
namespace WebMVC.Controllers
{
public class ExampleController : Controller
{
/* Use default global rate configuration */
[RateLimit]
public string GetReport(string param1)
{
return param1;
}
}
}