-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
75 lines (60 loc) · 2.29 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.ResponseCompression;
using Poc_ResponseCompression_And_RateLimit.Interfaces;
using Poc_ResponseCompression_And_RateLimit.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
// Register Services
builder.Services.AddScoped<IDividaService, DividaService>();
builder.Services.AddResponseCompression(options =>
{
// Configure the wishing algorithms
options.Providers.Add<GzipCompressionProvider>();
// Additional compression options
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/json" });
options.EnableForHttps = true;
});
builder.Services.AddRateLimiter(options =>
{
// Add status code 429 when limit reached
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// Add fixed window policy
options.AddFixedWindowLimiter(policyName: "FixedWindowRateLimiter", options =>
{
options.PermitLimit = 5;
options.Window = TimeSpan.FromMinutes(1);
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 0;
});
// Add limit reached message to user
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.StatusCode = 429;
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
await context.HttpContext.Response.WriteAsync(
$"Lots of requests. Try again after " +
$"{retryAfter.TotalMinutes} minutes(s). \n\n" +
$"Read more about our limits policy at " +
$"https://exemple.org/docs/ratelimiting.",
cancellationToken: token);
}
else
{
await context.HttpContext.Response.WriteAsync(
"Many requests. Try again later " +
"Read more about our limits policy at " +
"https://exemple.org/docs/ratelimiting.",
cancellationToken: token);
}
};
});
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.UseResponseCompression();
app.UseRateLimiter();
app.Run();