-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathBrowserFilter.cs
51 lines (41 loc) · 1.75 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//
using Microsoft.FeatureManagement;
namespace FeatureFlagDemo.FeatureManagement.FeatureFilters
{
[FilterAlias("Browser")]
public class BrowserFilter : IFeatureFilter
{
private const string Chrome = "Chrome";
private const string Edge = "Edge";
private readonly IHttpContextAccessor _httpContextAccessor;
public BrowserFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context)
{
BrowserFilterSettings settings = context.Parameters.Get<BrowserFilterSettings>() ?? new BrowserFilterSettings();
if (settings.AllowedBrowsers.Any(browser => browser.Equals(Chrome, StringComparison.OrdinalIgnoreCase)) && IsChrome())
{
return Task.FromResult(true);
}
else if (settings.AllowedBrowsers.Any(browser => browser.Equals(Edge, StringComparison.OrdinalIgnoreCase)) && IsEdge())
{
return Task.FromResult(true);
}
return Task.FromResult(false);
}
private bool IsChrome()
{
string userAgent = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"];
return userAgent != null && userAgent.Contains("Chrome", StringComparison.OrdinalIgnoreCase) && !userAgent.Contains("edge", StringComparison.OrdinalIgnoreCase);
}
private bool IsEdge()
{
// Return true if current request is sent from Edge browser
return false;
}
}
}