/
NavigationManagerExtensions.cs
722 lines (613 loc) · 31.7 KB
/
NavigationManagerExtensions.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Internal;
namespace Microsoft.AspNetCore.Components;
/// <summary>
/// Provides extension methods for the <see cref="NavigationManager"/> type.
/// </summary>
public static class NavigationManagerExtensions
{
private const string EmptyQueryParameterNameExceptionMessage = "Cannot have empty query parameter names.";
private delegate string? QueryParameterFormatter<TValue>(TValue value);
// We don't include mappings for Nullable types because we explicitly check for null values
// to see if the parameter should be excluded from the querystring. Therefore, we will only
// invoke these formatters for non-null values. We also get the underlying type of any Nullable
// types before performing lookups in this dictionary.
private static readonly Dictionary<Type, QueryParameterFormatter<object>> _queryParameterFormatters = new()
{
[typeof(string)] = value => Format((string)value)!,
[typeof(bool)] = value => Format((bool)value),
[typeof(DateTime)] = value => Format((DateTime)value),
[typeof(DateOnly)] = value => Format((DateOnly)value),
[typeof(TimeOnly)] = value => Format((TimeOnly)value),
[typeof(decimal)] = value => Format((decimal)value),
[typeof(double)] = value => Format((double)value),
[typeof(float)] = value => Format((float)value),
[typeof(Guid)] = value => Format((Guid)value),
[typeof(int)] = value => Format((int)value),
[typeof(long)] = value => Format((long)value),
};
private static string? Format(string? value)
=> value;
private static string Format(bool value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(bool? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(DateTime value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(DateTime? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(DateOnly value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(DateOnly? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(TimeOnly value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(TimeOnly? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(decimal value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(decimal? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(double value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(double? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(float value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(float? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(Guid value)
=> value.ToString(null, CultureInfo.InvariantCulture);
private static string? Format(Guid? value)
=> value?.ToString(null, CultureInfo.InvariantCulture);
private static string Format(int value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(int? value)
=> value?.ToString(CultureInfo.InvariantCulture);
private static string Format(long value)
=> value.ToString(CultureInfo.InvariantCulture);
private static string? Format(long? value)
=> value?.ToString(CultureInfo.InvariantCulture);
// Used for constructing a URI with a new querystring from an existing URI.
private struct QueryStringBuilder
{
private readonly StringBuilder _builder;
private bool _hasNewParameters;
public string UriWithQueryString => _builder.ToString();
public QueryStringBuilder(ReadOnlySpan<char> uriWithoutQueryString, int additionalCapacity = 0)
{
_builder = new(uriWithoutQueryString.Length + additionalCapacity);
_builder.Append(uriWithoutQueryString);
_hasNewParameters = false;
}
public void AppendParameter(ReadOnlySpan<char> encodedName, ReadOnlySpan<char> encodedValue)
{
if (!_hasNewParameters)
{
_hasNewParameters = true;
_builder.Append('?');
}
else
{
_builder.Append('&');
}
_builder.Append(encodedName);
_builder.Append('=');
_builder.Append(encodedValue);
}
}
// A utility for feeding a collection of parameter values into a QueryStringBuilder.
// This is used when generating a querystring with a query parameter that has multiple values.
private readonly struct QueryParameterSource<TValue>
{
private readonly IEnumerator<TValue?>? _enumerator;
private readonly QueryParameterFormatter<TValue>? _formatter;
public string EncodedName { get; }
// Creates an empty instance to simulate a source without any elements.
public QueryParameterSource(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new InvalidOperationException(EmptyQueryParameterNameExceptionMessage);
}
EncodedName = Uri.EscapeDataString(name);
_enumerator = default;
_formatter = default;
}
public QueryParameterSource(string name, IEnumerable<TValue?> values, QueryParameterFormatter<TValue> formatter)
: this(name)
{
_enumerator = values.GetEnumerator();
_formatter = formatter;
}
public bool TryAppendNextParameter(ref QueryStringBuilder builder)
{
if (_enumerator is null || !_enumerator.MoveNext())
{
return false;
}
var currentValue = _enumerator.Current;
if (currentValue is null)
{
// No-op to simulate appending a null parameter.
return true;
}
var formattedValue = _formatter!(currentValue);
var encodedValue = Uri.EscapeDataString(formattedValue!);
builder.AppendParameter(EncodedName, encodedValue);
return true;
}
}
// A utility for feeding an object of unknown type as one or more parameter values into
// a QueryStringBuilder.
private struct QueryParameterSource
{
private readonly QueryParameterSource<object> _source;
private string? _encodedValue;
public string EncodedName => _source.EncodedName;
public QueryParameterSource(string name, object? value)
{
if (value is null)
{
_source = new(name);
_encodedValue = default;
return;
}
var valueType = value.GetType();
if (valueType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(valueType))
{
// The provided value was of enumerable type, so we populate the underlying source.
var elementType = valueType.GetElementType()!;
var formatter = GetFormatterFromParameterValueType(elementType);
// This cast is inevitable; the values have to be boxed anyway to be formatted.
var values = ((IEnumerable)value).Cast<object>();
_source = new(name, values, formatter);
_encodedValue = default;
}
else
{
// The provided value was not of enumerable type, so we leave the underlying source
// empty and instead cache the encoded value to be appended later.
var formatter = GetFormatterFromParameterValueType(valueType);
var formattedValue = formatter(value);
_source = new(name);
_encodedValue = Uri.EscapeDataString(formattedValue!);
}
}
public bool TryAppendNextParameter(ref QueryStringBuilder builder)
{
if (_source.TryAppendNextParameter(ref builder))
{
// The underlying source of values had elements, so there is no more work to do here.
return true;
}
// Either we've run out of elements to append or the given value was not of enumerable
// type in the first place.
// If the value was not of enumerable type and has not been appended, append it
// and set it to null so we don't provide the value more than once.
if (_encodedValue is not null)
{
builder.AppendParameter(_source.EncodedName, _encodedValue);
_encodedValue = null;
return true;
}
return false;
}
}
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, bool value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, bool? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, DateTime value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, DateTime? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, DateOnly value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, DateOnly? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, TimeOnly value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, TimeOnly? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, decimal value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, decimal? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, double value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, double? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, float value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, float? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, Guid value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, Guid? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, int value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, int? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added or updated.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, long value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, long? value)
=> GetUriWithQueryParameter(navigationManager, name, Format(value));
/// <summary>
/// Returns a URI that is constructed by updating <see cref="NavigationManager.Uri"/> with a single parameter
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="name">The name of the parameter to add or update.</param>
/// <param name="value">The value of the parameter to add or update.</param>
/// <remarks>
/// If <paramref name="value"/> is <c>null</c>, the parameter will be removed if it exists in the URI.
/// Otherwise, it will be added or updated.
/// </remarks>
public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, string? value)
{
if (navigationManager is null)
{
throw new ArgumentNullException(nameof(navigationManager));
}
if (string.IsNullOrEmpty(name))
{
throw new InvalidOperationException(EmptyQueryParameterNameExceptionMessage);
}
var uri = navigationManager.Uri;
return value is null
? GetUriWithRemovedQueryParameter(uri, name)
: GetUriWithUpdatedQueryParameter(uri, name, value);
}
/// <summary>
/// Returns a URI constructed from <see cref="NavigationManager.Uri"/> with multiple parameters
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="parameters">The values to add, update, or remove.</param>
public static string GetUriWithQueryParameters(
this NavigationManager navigationManager,
IReadOnlyDictionary<string, object?> parameters)
=> GetUriWithQueryParameters(navigationManager, navigationManager.Uri, parameters);
/// <summary>
/// Returns a URI constructed from <paramref name="uri"/> except with multiple parameters
/// added, updated, or removed.
/// </summary>
/// <param name="navigationManager">The <see cref="NavigationManager"/>.</param>
/// <param name="uri">The URI with the query to modify.</param>
/// <param name="parameters">The values to add, update, or remove.</param>
public static string GetUriWithQueryParameters(
this NavigationManager navigationManager,
string uri,
IReadOnlyDictionary<string, object?> parameters)
{
if (navigationManager is null)
{
throw new ArgumentNullException(nameof(navigationManager));
}
if (uri is null)
{
throw new ArgumentNullException(nameof(uri));
}
if (!TryRebuildExistingQueryFromUri(uri, out var existingQueryStringEnumerable, out var newQueryStringBuilder))
{
// There was no existing query, so there is no need to allocate a new dictionary to cache
// encoded parameter values and track which parameters have been added.
return GetUriWithAppendedQueryParameters(uri, parameters);
}
var parameterSources = CreateParameterSourceDictionary(parameters);
// Rebuild the query, updating or removing parameters.
foreach (var pair in existingQueryStringEnumerable)
{
if (parameterSources.TryGetValue(pair.EncodedName, out var source))
{
if (source.TryAppendNextParameter(ref newQueryStringBuilder))
{
// We have just mutated the struct value so we need to overwrite the copy in the dictionary.
parameterSources[pair.EncodedName] = source;
}
}
else
{
newQueryStringBuilder.AppendParameter(pair.EncodedName.Span, pair.EncodedValue.Span);
}
}
// Append any parameters with non-null values that did not replace existing parameters.
foreach (var source in parameterSources.Values)
{
while (source.TryAppendNextParameter(ref newQueryStringBuilder))
{
// Read all parameters.
}
}
return newQueryStringBuilder.UriWithQueryString;
}
private static string GetUriWithUpdatedQueryParameter(string uri, string name, string value)
{
var encodedName = Uri.EscapeDataString(name);
var encodedValue = Uri.EscapeDataString(value);
if (!TryRebuildExistingQueryFromUri(uri, out var existingQueryStringEnumerable, out var newQueryStringBuilder))
{
// There was no existing query, so we can generate the new URI immediately.
return $"{uri}?{encodedName}={encodedValue}";
}
var didReplace = false;
foreach (var pair in existingQueryStringEnumerable)
{
if (pair.EncodedName.Span.Equals(encodedName, StringComparison.OrdinalIgnoreCase))
{
didReplace = true;
newQueryStringBuilder.AppendParameter(encodedName, encodedValue);
}
else
{
newQueryStringBuilder.AppendParameter(pair.EncodedName.Span, pair.EncodedValue.Span);
}
}
// If there was no matching parameter, add it to the end of the query.
if (!didReplace)
{
newQueryStringBuilder.AppendParameter(encodedName, encodedValue);
}
return newQueryStringBuilder.UriWithQueryString;
}
private static string GetUriWithRemovedQueryParameter(string uri, string name)
{
if (!TryRebuildExistingQueryFromUri(uri, out var existingQueryStringEnumerable, out var newQueryStringBuilder))
{
// There was no existing query, so the URI remains unchanged.
return uri;
}
var encodedName = Uri.EscapeDataString(name);
// Rebuild the query omitting parameters with a matching name.
foreach (var pair in existingQueryStringEnumerable)
{
if (!pair.EncodedName.Span.Equals(encodedName, StringComparison.OrdinalIgnoreCase))
{
newQueryStringBuilder.AppendParameter(pair.EncodedName.Span, pair.EncodedValue.Span);
}
}
return newQueryStringBuilder.UriWithQueryString;
}
private static string GetUriWithAppendedQueryParameters(
string uriWithoutQueryString,
IReadOnlyDictionary<string, object?> parameters)
{
var builder = new QueryStringBuilder(uriWithoutQueryString);
foreach (var (name, value) in parameters)
{
var source = new QueryParameterSource(name, value);
while (source.TryAppendNextParameter(ref builder))
{
// Read all parameters.
}
}
return builder.UriWithQueryString;
}
private static Dictionary<ReadOnlyMemory<char>, QueryParameterSource> CreateParameterSourceDictionary(
IReadOnlyDictionary<string, object?> parameters)
{
var parameterSources = new Dictionary<ReadOnlyMemory<char>, QueryParameterSource>(QueryParameterNameComparer.Instance);
foreach (var (name, value) in parameters)
{
var parameterSource = new QueryParameterSource(name, value);
parameterSources.Add(parameterSource.EncodedName.AsMemory(), parameterSource);
}
return parameterSources;
}
private static QueryParameterFormatter<object> GetFormatterFromParameterValueType(Type parameterValueType)
{
var underlyingParameterValueType = Nullable.GetUnderlyingType(parameterValueType) ?? parameterValueType;
if (!_queryParameterFormatters.TryGetValue(underlyingParameterValueType, out var formatter))
{
throw new InvalidOperationException(
$"Cannot format query parameters with values of type '{underlyingParameterValueType}'.");
}
return formatter;
}
private static bool TryRebuildExistingQueryFromUri(
string uri,
out QueryStringEnumerable existingQueryStringEnumerable,
out QueryStringBuilder newQueryStringBuilder)
{
var queryStartIndex = uri.IndexOf('?');
if (queryStartIndex < 0)
{
existingQueryStringEnumerable = default;
newQueryStringBuilder = default;
return false;
}
var query = uri.AsMemory(queryStartIndex);
existingQueryStringEnumerable = new(query);
var uriWithoutQueryString = uri.AsSpan(0, queryStartIndex);
newQueryStringBuilder = new(uriWithoutQueryString, query.Length);
return true;
}
}