How to use rate limit middleware in Blazor Server App

takeolexus 80 Reputation points
2023-07-17T04:36:49.5866667+00:00

I referred to the following pages.

https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-7.0

For example, I want to limit the index.razor page to 10 requests per minute.

I have the following code.

builder.Services.AddRateLimiter(_ => _
    .AddFixedWindowLimiter(policyName: "fixed", options =>
    {
        options.PermitLimit = 10;
        options.Window = TimeSpan.FromSeconds(60);
        options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        options.QueueLimit = 0;
    }));

   :
   :

app.UseRouting();
app.UseRateLimiter();

I tried writing the code as below but it didn't work.

@page "/counter"
@attribute [EnableRateLimiting("fixed")]

@using Microsoft.AspNetCore.RateLimiting

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;
    private void IncrementCount()
    {
        currentCount++;
    }
}

How to resolve it? Thanks.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,772 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,661 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,273 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 70,776 Reputation points
    2023-07-17T15:30:50.87+00:00

    Blazor server uses signalr to communicate to the browser, so middleware is not involved in the blazor event processing. From middleware point of view a blazor server app is a single request.

    You could override the navigation component.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-7.0

    note: blazor server does not have real page requests. It’s a component tree, and a page navigation just adds a different component to the tree.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.