/
PageRouteModelFactory.cs
189 lines (157 loc) · 7.48 KB
/
PageRouteModelFactory.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
// 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;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels;
internal sealed partial class PageRouteModelFactory
{
private static readonly string IndexFileName = "Index" + RazorViewEngine.ViewExtension;
private readonly RazorPagesOptions _options;
private readonly ILogger _logger;
private readonly string _normalizedRootDirectory;
private readonly string _normalizedAreaRootDirectory;
public PageRouteModelFactory(
RazorPagesOptions options,
ILogger logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_normalizedRootDirectory = NormalizeDirectory(options.RootDirectory);
_normalizedAreaRootDirectory = "/Areas/";
}
public PageRouteModel CreateRouteModel(string relativePath, string? routeTemplate)
{
var viewEnginePath = GetViewEnginePath(_normalizedRootDirectory, relativePath);
var routeModel = new PageRouteModel(relativePath, viewEnginePath);
PopulateRouteModel(routeModel, viewEnginePath, routeTemplate);
return routeModel;
}
public PageRouteModel? CreateAreaRouteModel(string relativePath, string? routeTemplate)
{
if (!TryParseAreaPath(relativePath, out var areaResult))
{
return null;
}
var routeModel = new PageRouteModel(relativePath, areaResult.viewEnginePath, areaResult.areaName);
var routePrefix = CreateAreaRoute(areaResult.areaName, areaResult.viewEnginePath);
PopulateRouteModel(routeModel, routePrefix, routeTemplate);
routeModel.RouteValues["area"] = areaResult.areaName;
return routeModel;
}
private static void PopulateRouteModel(PageRouteModel model, string pageRoute, string? routeTemplate)
{
model.RouteValues.Add("page", model.ViewEnginePath);
var selectorModel = CreateSelectorModel(pageRoute, routeTemplate);
model.Selectors.Add(selectorModel);
var fileName = Path.GetFileName(model.RelativePath);
if (!AttributeRouteModel.IsOverridePattern(routeTemplate) &&
string.Equals(IndexFileName, fileName, StringComparison.OrdinalIgnoreCase))
{
// For pages without an override route, and ending in /Index.cshtml, we want to allow
// incoming routing, but force outgoing routes to match to the path sans /Index.
selectorModel.AttributeRouteModel!.SuppressLinkGeneration = true;
var index = pageRoute.LastIndexOf('/');
var parentDirectoryPath = index == -1 ?
string.Empty :
pageRoute.Substring(0, index);
model.Selectors.Add(CreateSelectorModel(parentDirectoryPath, routeTemplate));
}
}
// Internal for unit testing
internal bool TryParseAreaPath(
string relativePath,
out (string areaName, string viewEnginePath) result)
{
// path = "/Areas/Products/Pages/Manage/Home.cshtml"
// Result ("Products", "/Manage/Home")
const string AreaPagesRoot = "/Pages/";
result = default;
Debug.Assert(relativePath.StartsWith('/'));
// Parse the area root directory.
var areaRootEndIndex = relativePath.IndexOf('/', startIndex: 1);
if (areaRootEndIndex == -1 ||
areaRootEndIndex >= relativePath.Length - 1 || // There's at least one token after the area root.
!relativePath.StartsWith(_normalizedAreaRootDirectory, StringComparison.OrdinalIgnoreCase)) // The path must start with area root.
{
Log.UnsupportedAreaPath(_logger, relativePath);
return false;
}
// The first directory that follows the area root is the area name.
var areaEndIndex = relativePath.IndexOf('/', startIndex: areaRootEndIndex + 1);
if (areaEndIndex == -1 || areaEndIndex == relativePath.Length)
{
Log.UnsupportedAreaPath(_logger, relativePath);
return false;
}
var areaName = relativePath.Substring(areaRootEndIndex + 1, areaEndIndex - areaRootEndIndex - 1);
// Ensure the next token is the "Pages" directory
if (string.Compare(relativePath, areaEndIndex, AreaPagesRoot, 0, AreaPagesRoot.Length, StringComparison.OrdinalIgnoreCase) != 0)
{
Log.UnsupportedAreaPath(_logger, relativePath);
return false;
}
// Include the trailing slash of the root directory at the start of the viewEnginePath
var pageNameIndex = areaEndIndex + AreaPagesRoot.Length - 1;
var viewEnginePath = relativePath.Substring(pageNameIndex, relativePath.Length - pageNameIndex - RazorViewEngine.ViewExtension.Length);
result = (areaName, viewEnginePath);
return true;
}
private static string GetViewEnginePath(string rootDirectory, string path)
{
// rootDirectory = "/Pages/AllMyPages/"
// path = "/Pages/AllMyPages/Home.cshtml"
// Result = "/Home"
Debug.Assert(path.StartsWith(rootDirectory, StringComparison.OrdinalIgnoreCase));
Debug.Assert(path.EndsWith(RazorViewEngine.ViewExtension, StringComparison.OrdinalIgnoreCase));
var startIndex = rootDirectory.Length - 1;
var endIndex = path.Length - RazorViewEngine.ViewExtension.Length;
return path.Substring(startIndex, endIndex - startIndex);
}
private static string CreateAreaRoute(string areaName, string viewEnginePath)
{
// AreaName = Products, ViewEnginePath = /List/Categories
// Result = /Products/List/Categories
Debug.Assert(!string.IsNullOrEmpty(areaName));
Debug.Assert(!string.IsNullOrEmpty(viewEnginePath));
Debug.Assert(viewEnginePath.StartsWith('/'));
return string.Create(1 + areaName.Length + viewEnginePath.Length, (areaName, viewEnginePath), (span, tuple) =>
{
var (areaNameValue, viewEnginePathValue) = tuple;
span[0] = '/';
span = span.Slice(1);
areaNameValue.AsSpan().CopyTo(span);
span = span.Slice(areaNameValue.Length);
viewEnginePathValue.AsSpan().CopyTo(span);
});
}
private static SelectorModel CreateSelectorModel(string prefix, string? routeTemplate)
{
return new SelectorModel
{
AttributeRouteModel = new AttributeRouteModel
{
Template = AttributeRouteModel.CombineTemplates(prefix, routeTemplate),
},
EndpointMetadata =
{
new PageRouteMetadata(prefix, routeTemplate)
}
};
}
private static string NormalizeDirectory(string directory)
{
Debug.Assert(directory.StartsWith('/'));
if (directory.Length > 1 && !directory.EndsWith('/'))
{
return directory + "/";
}
return directory;
}
private static partial class Log
{
[LoggerMessage(1, LogLevel.Warning, "The page at '{FilePath}' is located under the area root directory '/Areas/' but does not follow the path format '/Areas/AreaName/Pages/Directory/FileName.cshtml", EventName = "UnsupportedAreaPath")]
public static partial void UnsupportedAreaPath(ILogger log, string filePath);
}
}