Skip to content

Instantly share code, notes, and snippets.

@zarxor
Last active January 1, 2019 21:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zarxor/946ae56e1b90769369cb7d2e4f7aa2a7 to your computer and use it in GitHub Desktop.
Save zarxor/946ae56e1b90769369cb7d2e4f7aa2a7 to your computer and use it in GitHub Desktop.
Request throttling for .NET Core MVC
[AttributeUsage(AttributeTargets.Method)]
public class ThrottleAttribute : ActionFilterAttribute
{
public string Name { get; set; }
public int Seconds { get; set; }
public string Message { get; set; }
private static MemoryCache Cache { get; } = new MemoryCache(new MemoryCacheOptions());
public override void OnActionExecuting(ActionExecutingContext c)
{
var key = string.Concat(Name, "-", c.HttpContext.Request.HttpContext.Connection.RemoteIpAddress);
if (!Cache.TryGetValue(key, out bool entry))
{
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(Seconds));
Cache.Set(key, true, cacheEntryOptions);
}
else
{
if (string.IsNullOrEmpty(Message))
Message = "You may only perform this action every {n} seconds.";
c.Result = new ContentResult {Content = Message.Replace("{n}", Seconds.ToString())};
c.HttpContext.Response.StatusCode = (int) HttpStatusCode.Conflict;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment