Last active
January 1, 2019 21:00
-
-
Save zarxor/946ae56e1b90769369cb7d2e4f7aa2a7 to your computer and use it in GitHub Desktop.
Request throttling for .NET Core MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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