Repository navigation
Expand file tree
/
Copy pathSpaRouteExtensions.cs
More file actions
72 lines (61 loc) · 2.47 KB
/
Copy pathSpaRouteExtensions.cs
File metadata and controls
72 lines (61 loc) · 2.47 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SpaServices;
// Putting in this namespace so it's always available whenever MapRoute is
namespace Microsoft.AspNetCore.Builder
{
public static class SpaRouteExtensions
{
private const string ClientRouteTokenName = "clientRoute";
public static void MapSpaFallbackRoute(
this IRouteBuilder routeBuilder,
string name,
object defaults,
object constraints = null,
object dataTokens = null)
{
MapSpaFallbackRoute(
routeBuilder,
name,
/* templatePrefix */ null,
defaults,
constraints,
dataTokens);
}
public static void MapSpaFallbackRoute(
this IRouteBuilder routeBuilder,
string name,
string templatePrefix,
object defaults,
object constraints = null,
object dataTokens = null)
{
var template = CreateRouteTemplate(templatePrefix);
var constraintsDict = ObjectToDictionary(constraints);
constraintsDict.Add(ClientRouteTokenName, new SpaRouteConstraint(ClientRouteTokenName));
routeBuilder.MapRoute(name, template, defaults, constraintsDict, dataTokens);
}
private static string CreateRouteTemplate(string templatePrefix)
{
templatePrefix = templatePrefix ?? string.Empty;
if (templatePrefix.Contains("?"))
{
// TODO: Consider supporting this. The {*clientRoute} part should be added immediately before the '?'
throw new ArgumentException("SPA fallback route templates don't support querystrings");
}
if (templatePrefix.Contains("#"))
{
throw new ArgumentException(
"SPA fallback route templates should not include # characters. The hash part of a URI does not get sent to the server.");
}
if (templatePrefix != string.Empty && !templatePrefix.EndsWith("/"))
{
templatePrefix += "/";
}
return templatePrefix + $"{{*{ClientRouteTokenName}}}";
}
private static IDictionary<string, object> ObjectToDictionary(object value)
=> value as IDictionary<string, object> ?? new RouteValueDictionary(value);
}
}