Joydip Kanjilal
Contributor

How to implement rate limiting in ASP.NET Core

how-to
Oct 07, 20195 mins
C#Microsoft .NETSoftware Development

Take advantage of rate limiting in ASP.NET Core to prevent malicious attacks on your web application.

When building web applications, you might often want to control the frequency of user requests to prevent malicious attacks. In other words, you might want to limit the number of requests coming from an IP address during a short timespan to mitigate denial-of-service attacks. This process is known as rate limiting.

Rate limiting enables you to control the number of requests that a client can make to an endpoint. Prior to ASP.NET Core, you had to write a lot of boilerplate code to implement rate limiting. However, implementing rate limiting is easy in ASP.NET Core. In this article, we’ll examine how we can work with rate limiting in ASP.NET Core.

Create an ASP.NET Core API project

First off, let’s create an ASP.NET Core project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.NET Core Web Application” shown next, select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the drop-down list at the top.
  8. Select “API” as the project template to create a new ASP.NET Core API application. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create.

Following these steps should create a new ASP.NET Core API project in Visual Studio. We’ll use this project to implement rate limiting in the subsequent sections of this article.

Install rate limiting middleware in ASP.NET Core

To implement rate limiting in ASP.NET Core, we will take advantage of a rate limiting middleware package for ASP.NET Core. You can use this middleware to set rate limits for various scenarios, such as allowing an IP or a range of IPs to make a specified number of calls within a specific time interval. The time interval can be per second, per minute, per n minutes, etc.

After you have created an ASP.NET Core API project in Visual Studio, the next step is to install the necessary NuGet packages. The package you will need to implement rate limiting is AspNetCoreRateLimit. You can install this package from the NuGet Package Manager inside Visual Studio, or by entering the following command in the .NET CLI.

dotnet add package AspNetCoreRateLimit

You can learn more about the AspNetCoreRateLimit package from its GitHub repository here.  

Configure rate limiting middleware in ASP.NET Core

Now that the AspNetCoreRateLimit package is installed in your project, write the following code in the ConfigureServices method to add the middleware to the request-response pipeline.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion
            (CompatibilityVersion.Version_2_2);
            services.AddOptions();
            services.AddMemoryCache();
            services.Configure<IpRateLimitOptions>
            (Configuration.GetSection("IpRateLimit"));
            services.AddSingleton<IIpPolicyStore,
            MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore,
            MemoryCacheRateLimitCounterStore>();
            services.AddSingleton<IRateLimitConfiguration,
            RateLimitConfiguration>();
            services.AddHttpContextAccessor();
        }

Note the usage of the section name IpRateLimit in the code snippet shown above. This section in the appsettings.json file will contain the metadata for rate limiting.

Next, write the following code in the Configure method to use the rate limiting middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseIpRateLimiting();
            app.UseMvcWithDefaultRoute();
        }

Finally, write the following code in the appsettings.json file. Note how the rate limit rules are specified. A rate limit rule comprises an endpoint, a period of time, and a limit.

{
  "IpRateLimit": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "RealIPHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "HttpStatusCode": 429,
    "GeneralRules": [
      {
        "Endpoint": "*:/api/*",
        "Period": "1m",
        "Limit": 5
      }
    ]
  }
}

The rate limit rule above will make sure that endpoints that have “/api” in the URI will be limited to five requests in any one-minute period.

Test the rate limit in your ASP.NET Core API

To run the application, press the Ctrl and F5 keys together. When you run the application, the Get method of the ValuesController (this is the default controller created for you by Visual Studio) will be executed and the following messages will be displayed.

value1

value2

Now refresh the web page five times and you should see the following message.

aspnetcoreratelimit max calls IDG

The maximum number of calls to your ASP.NET Core API has been reached.

For illustrative purposes, I’ve set the rate limit to five. Naturally, you should change the rate limit according to your application’s needs. You can store rate limits in a database or in the cache memory. The AspNetCoreRateLimit rate limit middleware allows you to update rate limits at runtime as well.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author