-
Notifications
You must be signed in to change notification settings - Fork 114
/
BrowserFilter.cs
72 lines (59 loc) · 2.51 KB
/
BrowserFilter.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
using Microsoft.FeatureManagement;
namespace BlazorServerApp
{
[FilterAlias("Browser")]
public class BrowserFilter : IFeatureFilter
{
private const string Chrome = "Chrome";
private const string Edge = "Edge";
private const string Firefox = "Firefox";
private readonly UserAgentContext _userAgentContextProvider;
public BrowserFilter(UserAgentContext userAgentContextProvider)
{
_userAgentContextProvider = userAgentContextProvider ?? throw new ArgumentNullException(nameof(userAgentContextProvider));
}
public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
{
BrowserFilterSettings settings = context.Parameters.Get<BrowserFilterSettings>() ?? new BrowserFilterSettings();
string userAgentContext = _userAgentContextProvider.UserAgent;
if (settings.AllowedBrowsers.Any(browser => browser.Equals(Chrome, StringComparison.OrdinalIgnoreCase)) && IsChromeBrowser(userAgentContext))
{
return Task.FromResult(true);
}
else if (settings.AllowedBrowsers.Any(browser => browser.Equals(Edge, StringComparison.OrdinalIgnoreCase)) && IsEdgeBrowser(userAgentContext))
{
return Task.FromResult(true);
}
else if (settings.AllowedBrowsers.Any(browser => browser.Equals(Firefox, StringComparison.OrdinalIgnoreCase)) && IsFirefoxBrowser(userAgentContext))
{
return Task.FromResult(true);
}
return Task.FromResult(false);
}
private static bool IsChromeBrowser(string userAgentContext)
{
if (userAgentContext == null)
{
return false;
}
return userAgentContext.Contains("chrome", StringComparison.OrdinalIgnoreCase) &&
!userAgentContext.Contains("edg", StringComparison.OrdinalIgnoreCase);
}
private static bool IsEdgeBrowser(string userAgentContext)
{
if (userAgentContext == null)
{
return false;
}
return userAgentContext.Contains("edg", StringComparison.OrdinalIgnoreCase);
}
private static bool IsFirefoxBrowser(string userAgentContext)
{
if (userAgentContext == null)
{
return false;
}
return userAgentContext.Contains("firefox", StringComparison.OrdinalIgnoreCase);
}
}
}