|
| 1 | +using Microsoft.FeatureManagement; |
| 2 | + |
| 3 | +namespace BlazorServerApp |
| 4 | +{ |
| 5 | + [FilterAlias("Browser")] |
| 6 | + public class BrowserFilter : IFeatureFilter |
| 7 | + { |
| 8 | + private const string Chrome = "Chrome"; |
| 9 | + private const string Edge = "Edge"; |
| 10 | + private const string Firefox = "Firefox"; |
| 11 | + |
| 12 | + private readonly UserAgentContext _userAgentContextProvider; |
| 13 | + |
| 14 | + public BrowserFilter(UserAgentContext userAgentContextProvider) |
| 15 | + { |
| 16 | + _userAgentContextProvider = userAgentContextProvider ?? throw new ArgumentNullException(nameof(userAgentContextProvider)); |
| 17 | + } |
| 18 | + |
| 19 | + public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context) |
| 20 | + { |
| 21 | + BrowserFilterSettings settings = context.Parameters.Get<BrowserFilterSettings>() ?? new BrowserFilterSettings(); |
| 22 | + |
| 23 | + string userAgentContext = _userAgentContextProvider.UserAgent; |
| 24 | + |
| 25 | + if (settings.AllowedBrowsers.Any(browser => browser.Equals(Chrome, StringComparison.OrdinalIgnoreCase)) && IsChromeBrowser(userAgentContext)) |
| 26 | + { |
| 27 | + return Task.FromResult(true); |
| 28 | + } |
| 29 | + else if (settings.AllowedBrowsers.Any(browser => browser.Equals(Edge, StringComparison.OrdinalIgnoreCase)) && IsEdgeBrowser(userAgentContext)) |
| 30 | + { |
| 31 | + return Task.FromResult(true); |
| 32 | + } |
| 33 | + else if (settings.AllowedBrowsers.Any(browser => browser.Equals(Firefox, StringComparison.OrdinalIgnoreCase)) && IsFirefoxBrowser(userAgentContext)) |
| 34 | + { |
| 35 | + return Task.FromResult(true); |
| 36 | + } |
| 37 | + |
| 38 | + return Task.FromResult(false); |
| 39 | + } |
| 40 | + |
| 41 | + private static bool IsChromeBrowser(string userAgentContext) |
| 42 | + { |
| 43 | + if (userAgentContext == null) |
| 44 | + { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + return userAgentContext.Contains("chrome", StringComparison.OrdinalIgnoreCase) && |
| 49 | + !userAgentContext.Contains("edg", StringComparison.OrdinalIgnoreCase); |
| 50 | + } |
| 51 | + |
| 52 | + private static bool IsEdgeBrowser(string userAgentContext) |
| 53 | + { |
| 54 | + if (userAgentContext == null) |
| 55 | + { |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | + return userAgentContext.Contains("edg", StringComparison.OrdinalIgnoreCase); |
| 60 | + } |
| 61 | + |
| 62 | + private static bool IsFirefoxBrowser(string userAgentContext) |
| 63 | + { |
| 64 | + if (userAgentContext == null) |
| 65 | + { |
| 66 | + return false; |
| 67 | + } |
| 68 | + |
| 69 | + return userAgentContext.Contains("firefox", StringComparison.OrdinalIgnoreCase); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments