How to use rate limit middleware in Blazor Server App

takeolexus 180 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.

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
Developer technologies | C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    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.