Request throttling in .NET Core MVC

Why do I need to throttle usage?

Security in apis are important and we might not want the apis we build to be overly used. This could be to prevent DDoS attacks or to make sure no one tries to brute-force-use your api. To solve this problem I built a small attribute function that allows for throttling of a specific endpoint.

When I started writing this i got alot of inspiration from this post on stack overflow.

Attribute code

Here is the code for the throttling attribute

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()

            Cache.Set(key, true, cacheEntryOptions);
            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;

Example usage

public class ActionsController : Controller
    // GET /api/actions/throttle
    // Only allow access every 5 seconds
    [Throttle(Name = "ThrottleTest", Seconds = 5)]
    public object GetThrottle() => new
        Message = "OK!"


Profile image

Johan Boström

I'm a system architect, developer and solution expert, with experience in web-, application-, server- and windows service development with main focus on .NET / C#. Special skills with many kinds of CMS-tools, like EPiServer, Umbraco and Litium Studio.