-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathHttpUserAgentParserAccessor.cs
More file actions
50 lines (44 loc) · 1.62 KB
/
HttpUserAgentParserAccessor.cs
File metadata and controls
50 lines (44 loc) · 1.62 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
// Copyright © https://myCSharp.de - all rights reserved
using Microsoft.AspNetCore.Http;
using MyCSharp.HttpUserAgentParser.Providers;
namespace MyCSharp.HttpUserAgentParser.AspNetCore;
/// <summary>
/// Default implementation of <see cref="IHttpUserAgentParserAccessor"/> for ASP.NET Core applications.
/// </summary>
/// <remarks>
/// Extracts and parses the User-Agent header from HTTP requests.
/// Register via <c>services.AddHttpUserAgentParser().AddHttpUserAgentParserAccessor()</c>.
/// </remarks>
/// <param name="httpUserAgentParser">The parser provider to use for parsing.</param>
public class HttpUserAgentParserAccessor(IHttpUserAgentParserProvider httpUserAgentParser)
: IHttpUserAgentParserAccessor
{
private readonly IHttpUserAgentParserProvider _httpUserAgentParser = httpUserAgentParser;
/// <inheritdoc/>
/// <example>
/// <code>
/// string? userAgent = accessor.GetHttpContextUserAgent(httpContext);
/// </code>
/// </example>
public string? GetHttpContextUserAgent(HttpContext httpContext)
=> httpContext.GetUserAgentString();
/// <inheritdoc/>
/// <example>
/// <code>
/// HttpUserAgentInformation? info = accessor.Get(httpContext);
/// if (info != null)
/// {
/// Console.WriteLine(info.Value.Name);
/// }
/// </code>
/// </example>
public HttpUserAgentInformation? Get(HttpContext httpContext)
{
string? httpUserAgent = GetHttpContextUserAgent(httpContext);
if (string.IsNullOrEmpty(httpUserAgent))
{
return null;
}
return _httpUserAgentParser.Parse(httpUserAgent);
}
}