Take advantage of rate limiting in ASP.NET Core to prevent malicious attacks on your web application. Credit: Pete Smithies 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Click Create. 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. Select “API” as the project template to create a new ASP.NET Core API application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. 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. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos