-
Notifications
You must be signed in to change notification settings - Fork 732
/
HeaderKey.cs
72 lines (61 loc) · 2.54 KB
/
HeaderKey.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.HeaderParsing;
/// <summary>
/// Used to indicate which header to parse.
/// </summary>
/// <typeparam name="T">The type of the header value.</typeparam>
[SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Header keys are never disposed, so we don't bother with this.")]
[SuppressMessage("Blocker Bug", "S2931:Classes with \"IDisposable\" members should implement \"IDisposable\"", Justification = "Header keys are never disposed, so we don't bother with this.")]
public sealed class HeaderKey<T>
where T : notnull
{
/// <summary>
/// Gets the name of the header.
/// </summary>
public string Name { get; }
internal bool HasDefaultValue { get; }
internal T? DefaultValue { get; }
internal int Position { get; }
internal HeaderParser<T> Parser { get; }
private readonly IMemoryCache? _valueCache;
internal HeaderKey(string name, HeaderParser<T> parser, int position, int maxCachedValues = 0)
{
Name = name;
Position = position;
Parser = parser;
if (maxCachedValues > 0)
{
var o = new MemoryCacheOptions
{
SizeLimit = maxCachedValues,
};
_valueCache = new MemoryCache(Options.Create(o));
}
}
internal HeaderKey(string name, HeaderParser<T> parser, int position, int maxCachedValues, T defaultValue)
: this(name, parser, position, maxCachedValues)
{
DefaultValue = defaultValue;
HasDefaultValue = true;
}
/// <summary>
/// Returns a string representing this instance.
/// </summary>
/// <returns>
/// The name of this instance.
/// </returns>
public override string ToString() => Name;
private static readonly MemoryCacheEntryOptions _cacheEntryOptions = new()
{
Size = 1,
};
internal bool TryParse(StringValues values, out T? result, out string? error) => Parser.TryParse(values, out result, out error);
internal void AddCachedValue(StringValues values, object o) => _valueCache!.Set(values, o, _cacheEntryOptions);
internal object? GetCachedValue(StringValues values) => _valueCache!.Get(values);
internal bool Cacheable => _valueCache != null;
}