-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientHintsRegistration.cs
More file actions
87 lines (77 loc) · 2.76 KB
/
HttpClientHintsRegistration.cs
File metadata and controls
87 lines (77 loc) · 2.76 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright © https://myCSharp.de - all rights reserved
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace MyCSharp.HttpClientHints.AspNetCore;
/// <summary>
/// Extension methods for registering and configuring HTTP Client Hints middleware.
/// </summary>
public static class HttpClientHintsRegistration
{
/// <summary>
/// Adds HTTP Client Hints configuration to the service collection.
/// </summary>
/// <param name="services">The service collection to add the configuration to.</param>
/// <param name="config">An optional action to configure <see cref="HttpClientHintsOptions"/>.</param>
public static IServiceCollection AddHttpClientHints(this IServiceCollection services, Action<HttpClientHintsOptions>? config = null)
{
HttpClientHintsOptions httpClientHintsConfig = new();
config?.Invoke(httpClientHintsConfig);
// lifetime
string? lifeTime;
if (httpClientHintsConfig.Lifetime is TimeSpan lifetime)
{
lifeTime = lifetime.TotalSeconds.ToString("0.##", provider: null); // ignore decimals
}
else
{
lifeTime = null;
}
// headers
List<string> headers = [];
if (httpClientHintsConfig.UserAgent)
{
headers.Add("User-Agent");
headers.Add("Sec-CH-UA");
}
if (httpClientHintsConfig.Platform)
{
headers.Add("Sec-CH-UA-Platform");
headers.Add("Sec-CH-UA-Platform-Version");
}
if (httpClientHintsConfig.Architecture)
{
headers.Add("Sec-CH-UA-Arch");
headers.Add("Sec-CH-UA-Bitness");
}
if (httpClientHintsConfig.Device)
{
headers.Add("Sec-CH-UA-Model");
}
if (httpClientHintsConfig.Mobile)
{
headers.Add("Sec-CH-UA-Mobile");
}
// customization
if (httpClientHintsConfig.Additional is not null)
{
headers.AddRange(httpClientHintsConfig.Additional);
}
// register middleware config
services.Configure<HttpClientHintsMiddlewareConfig>(o =>
{
o.ResponseHeader = string.Join(", ", headers);
o.LifeTime = lifeTime;
});
return services;
}
/// <summary>
/// Adds the <see cref="HttpClientHintsRequestMiddleware"/> to the application's request pipeline.
/// </summary>
/// <param name="app">The application builder.</param>
/// <returns>The application builder with the middleware added.</returns>
public static IApplicationBuilder UseHttpClientHints(this IApplicationBuilder app)
{
app.UseMiddleware<HttpClientHintsRequestMiddleware>();
return app;
}
}