This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
/
LinkTagHelper.cs
542 lines (466 loc) · 21.7 KB
/
LinkTagHelper.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.TagHelpers.Internal;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Caching.Memory;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
/// <summary>
/// <see cref="ITagHelper"/> implementation targeting <link> elements that supports fallback href paths.
/// </summary>
/// <remarks>
/// The tag helper won't process for cases with just the 'href' attribute.
/// </remarks>
[HtmlTargetElement("link", Attributes = HrefIncludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = HrefExcludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefIncludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefExcludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestClassAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestPropertyAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestValueAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = AppendVersionAttributeName, TagStructure = TagStructure.WithoutEndTag)]
public class LinkTagHelper : UrlResolutionTagHelper
{
private static readonly string FallbackJavaScriptResourceName =
typeof(LinkTagHelper).Namespace + ".compiler.resources.LinkTagHelper_FallbackJavaScript.js";
private const string HrefIncludeAttributeName = "asp-href-include";
private const string HrefExcludeAttributeName = "asp-href-exclude";
private const string FallbackHrefAttributeName = "asp-fallback-href";
private const string FallbackHrefIncludeAttributeName = "asp-fallback-href-include";
private const string FallbackHrefExcludeAttributeName = "asp-fallback-href-exclude";
private const string FallbackTestClassAttributeName = "asp-fallback-test-class";
private const string FallbackTestPropertyAttributeName = "asp-fallback-test-property";
private const string FallbackTestValueAttributeName = "asp-fallback-test-value";
private const string AppendVersionAttributeName = "asp-append-version";
private const string HrefAttributeName = "href";
private const string RelAttributeName = "rel";
private static readonly Func<Mode, Mode, int> Compare = (a, b) => a - b;
private FileVersionProvider _fileVersionProvider;
private static readonly ModeAttributes<Mode>[] ModeDetails = new[] {
// Regular src with file version alone
new ModeAttributes<Mode>(Mode.AppendVersion, new[] { AppendVersionAttributeName }),
// Globbed Href (include only) no static href
new ModeAttributes<Mode>(Mode.GlobbedHref, new [] { HrefIncludeAttributeName }),
// Globbed Href (include & exclude), no static href
new ModeAttributes<Mode>(Mode.GlobbedHref, new [] { HrefIncludeAttributeName, HrefExcludeAttributeName }),
// Fallback with static href
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
// Fallback with globbed href (include only)
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefIncludeAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
// Fallback with globbed href (include & exclude)
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefIncludeAttributeName,
FallbackHrefExcludeAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
};
private StringWriter _stringWriter;
/// <summary>
/// Creates a new <see cref="LinkTagHelper"/>.
/// </summary>
/// <param name="hostingEnvironment">The <see cref="IHostingEnvironment"/>.</param>
/// <param name="cache">The <see cref="IMemoryCache"/>.</param>
/// <param name="htmlEncoder">The <see cref="HtmlEncoder"/>.</param>
/// <param name="javaScriptEncoder">The <see cref="JavaScriptEncoder"/>.</param>
/// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory"/>.</param>
public LinkTagHelper(
IHostingEnvironment hostingEnvironment,
IMemoryCache cache,
HtmlEncoder htmlEncoder,
JavaScriptEncoder javaScriptEncoder,
IUrlHelperFactory urlHelperFactory)
: base(urlHelperFactory, htmlEncoder)
{
HostingEnvironment = hostingEnvironment;
Cache = cache;
JavaScriptEncoder = javaScriptEncoder;
}
/// <inheritdoc />
public override int Order
{
get
{
return -1000;
}
}
/// <summary>
/// Address of the linked resource.
/// </summary>
/// <remarks>
/// Passed through to the generated HTML in all cases.
/// </remarks>
[HtmlAttributeName(HrefAttributeName)]
public string Href { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to load.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// </summary>
[HtmlAttributeName(HrefIncludeAttributeName)]
public string HrefInclude { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to exclude from loading.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// Must be used in conjunction with <see cref="HrefInclude"/>.
/// </summary>
[HtmlAttributeName(HrefExcludeAttributeName)]
public string HrefExclude { get; set; }
/// <summary>
/// The URL of a CSS stylesheet to fallback to in the case the primary one fails.
/// </summary>
[HtmlAttributeName(FallbackHrefAttributeName)]
public string FallbackHref { get; set; }
/// <summary>
/// Value indicating if file version should be appended to the href urls.
/// </summary>
/// <remarks>
/// If <c>true</c> then a query string "v" with the encoded content of the file is added.
/// </remarks>
[HtmlAttributeName(AppendVersionAttributeName)]
public bool? AppendVersion { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to fallback to in the case the primary
/// one fails.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// </summary>
[HtmlAttributeName(FallbackHrefIncludeAttributeName)]
public string FallbackHrefInclude { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to exclude from the fallback list, in
/// the case the primary one fails.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// Must be used in conjunction with <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackHrefExcludeAttributeName)]
public string FallbackHrefExclude { get; set; }
/// <summary>
/// The class name defined in the stylesheet to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestProperty"/> and <see cref="FallbackTestValue"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestClassAttributeName)]
public string FallbackTestClass { get; set; }
/// <summary>
/// The CSS property name to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestClass"/> and <see cref="FallbackTestValue"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestPropertyAttributeName)]
public string FallbackTestProperty { get; set; }
/// <summary>
/// The CSS property value to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestClass"/> and <see cref="FallbackTestProperty"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestValueAttributeName)]
public string FallbackTestValue { get; set; }
protected IHostingEnvironment HostingEnvironment { get; }
protected IMemoryCache Cache { get; }
protected JavaScriptEncoder JavaScriptEncoder { get; }
// Internal for ease of use when testing.
protected internal GlobbingUrlBuilder GlobbingUrlBuilder { get; set; }
// Shared writer for determining the string content of a TagHelperAttribute's Value.
private StringWriter StringWriter
{
get
{
if (_stringWriter == null)
{
_stringWriter = new StringWriter();
}
return _stringWriter;
}
}
/// <inheritdoc />
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
// Pass through attribute that is also a well-known HTML attribute.
if (Href != null)
{
output.CopyHtmlAttribute(HrefAttributeName, context);
}
// If there's no "href" attribute in output.Attributes this will noop.
ProcessUrlAttribute(HrefAttributeName, output);
// Retrieve the TagHelperOutput variation of the "href" attribute in case other TagHelpers in the
// pipeline have touched the value. If the value is already encoded this LinkTagHelper may
// not function properly.
Href = output.Attributes[HrefAttributeName]?.Value as string;
Mode mode;
if (!AttributeMatcher.TryDetermineMode(context, ModeDetails, Compare, out mode))
{
// No attributes matched so we have nothing to do
return;
}
if (AppendVersion == true)
{
EnsureFileVersionProvider();
if (Href != null)
{
var index = output.Attributes.IndexOfName(HrefAttributeName);
var existingAttribute = output.Attributes[index];
output.Attributes[index] = new TagHelperAttribute(
existingAttribute.Name,
_fileVersionProvider.AddFileVersionToPath(Href),
existingAttribute.ValueStyle);
}
}
var builder = output.PostElement;
builder.Clear();
if (mode == Mode.GlobbedHref || mode == Mode.Fallback && !string.IsNullOrEmpty(HrefInclude))
{
BuildGlobbedLinkTags(output.Attributes, builder);
if (string.IsNullOrEmpty(Href))
{
// Only HrefInclude is specified. Don't render the original tag.
output.TagName = null;
output.Content.SetHtmlContent(HtmlString.Empty);
}
}
if (mode == Mode.Fallback && HasStyleSheetLinkType(output.Attributes))
{
string resolvedUrl;
if (TryResolveUrl(FallbackHref, resolvedUrl: out resolvedUrl))
{
FallbackHref = resolvedUrl;
}
BuildFallbackBlock(output.Attributes, builder);
}
}
private void BuildGlobbedLinkTags(TagHelperAttributeList attributes, TagHelperContent builder)
{
EnsureGlobbingUrlBuilder();
// Build a <link /> tag for each matched href.
var urls = GlobbingUrlBuilder.BuildUrlList(null, HrefInclude, HrefExclude);
for (var i = 0; i < urls.Count; i++)
{
var url = urls[i];
// "url" values come from bound attributes and globbing. Must always be non-null.
Debug.Assert(url != null);
if (string.Equals(Href, url, StringComparison.OrdinalIgnoreCase))
{
// Don't build duplicate link tag for the original href url.
continue;
}
BuildLinkTag(url, attributes, builder);
}
}
private void BuildFallbackBlock(TagHelperAttributeList attributes, TagHelperContent builder)
{
EnsureGlobbingUrlBuilder();
var fallbackHrefs = GlobbingUrlBuilder.BuildUrlList(
FallbackHref,
FallbackHrefInclude,
FallbackHrefExclude);
if (fallbackHrefs.Count == 0)
{
return;
}
builder.AppendHtml(HtmlString.NewLine);
// Build the <meta /> tag that's used to test for the presence of the stylesheet
builder
.AppendHtml("<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"")
.Append(FallbackTestClass)
.AppendHtml("\" />");
// Build the <script /> tag that checks the effective style of <meta /> tag above and renders the extra
// <link /> tag to load the fallback stylesheet if the test CSS property value is found to be false,
// indicating that the primary stylesheet failed to load.
// GetEmbeddedJavaScript returns JavaScript to which we add '"{0}","{1}",{2});'
builder
.AppendHtml("<script>")
.AppendHtml(JavaScriptResources.GetEmbeddedJavaScript(FallbackJavaScriptResourceName))
.AppendHtml("\"")
.AppendHtml(JavaScriptEncoder.Encode(FallbackTestProperty))
.AppendHtml("\",\"")
.AppendHtml(JavaScriptEncoder.Encode(FallbackTestValue))
.AppendHtml("\",");
AppendFallbackHrefs(builder, fallbackHrefs);
builder.AppendHtml(", \"");
// Perf: Avoid allocating enumerator
for (var i = 0; i < attributes.Count; i++)
{
var attribute = attributes[i];
if (string.Equals(attribute.Name, HrefAttributeName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
attribute.WriteTo(StringWriter, HtmlEncoder);
StringWriter.Write(' ');
}
var stringBuilder = StringWriter.GetStringBuilder();
var scriptTags = stringBuilder.ToString();
stringBuilder.Clear();
var encodedScriptTags = JavaScriptEncoder.Encode(scriptTags);
builder.AppendHtml(encodedScriptTags);
builder.AppendHtml("\");</script>");
}
private bool HasStyleSheetLinkType(TagHelperAttributeList attributes)
{
TagHelperAttribute relAttribute;
if (!attributes.TryGetAttribute(RelAttributeName, out relAttribute) ||
relAttribute.Value == null)
{
return false;
}
var attributeValue = relAttribute.Value;
var contentValue = attributeValue as IHtmlContent;
var stringValue = attributeValue as string;
if (contentValue != null)
{
contentValue.WriteTo(StringWriter, HtmlEncoder);
stringValue = StringWriter.ToString();
// Reset writer
StringWriter.GetStringBuilder().Clear();
}
else if (stringValue == null)
{
stringValue = attributeValue.ToString();
}
var hasRelStylesheet = string.Equals("stylesheet", stringValue, StringComparison.Ordinal);
return hasRelStylesheet;
}
private void AppendFallbackHrefs(TagHelperContent builder, IReadOnlyList<string> fallbackHrefs)
{
builder.AppendHtml("[");
var firstAdded = false;
// Perf: Avoid allocating enumerator
for (var i = 0; i < fallbackHrefs.Count; i++)
{
if (firstAdded)
{
builder.AppendHtml(",\"");
}
else
{
builder.AppendHtml("\"");
firstAdded = true;
}
// fallbackHrefs come from bound attributes (a C# context) and globbing. Must always be non-null.
Debug.Assert(fallbackHrefs[i] != null);
var valueToWrite = fallbackHrefs[i];
if (AppendVersion == true)
{
valueToWrite = _fileVersionProvider.AddFileVersionToPath(fallbackHrefs[i]);
}
// Must HTML-encode the href attribute value to ensure the written <link/> element is valid. Must also
// JavaScript-encode that value to ensure the doc.write() statement is valid.
valueToWrite = HtmlEncoder.Encode(valueToWrite);
valueToWrite = JavaScriptEncoder.Encode(valueToWrite);
builder.AppendHtml(valueToWrite);
builder.AppendHtml("\"");
}
builder.AppendHtml("]");
}
private void EnsureGlobbingUrlBuilder()
{
if (GlobbingUrlBuilder == null)
{
GlobbingUrlBuilder = new GlobbingUrlBuilder(
HostingEnvironment.WebRootFileProvider,
Cache,
ViewContext.HttpContext.Request.PathBase);
}
}
private void EnsureFileVersionProvider()
{
if (_fileVersionProvider == null)
{
_fileVersionProvider = new FileVersionProvider(
HostingEnvironment.WebRootFileProvider,
Cache,
ViewContext.HttpContext.Request.PathBase);
}
}
private void BuildLinkTag(string href, TagHelperAttributeList attributes, TagHelperContent builder)
{
builder.AppendHtml("<link ");
var addHref = true;
// Perf: Avoid allocating enumerator
for (var i = 0; i < attributes.Count; i++)
{
var attribute = attributes[i];
if (string.Equals(attribute.Name, HrefAttributeName, StringComparison.OrdinalIgnoreCase))
{
addHref = false;
AppendVersionedHref(attribute.Name, href, builder);
}
else
{
attribute.CopyTo(builder);
builder.AppendHtml(" ");
}
}
if (addHref)
{
AppendVersionedHref(HrefAttributeName, href, builder);
}
builder.AppendHtml("/>");
}
private void AppendVersionedHref(string hrefName, string hrefValue, TagHelperContent builder)
{
if (AppendVersion == true)
{
hrefValue = _fileVersionProvider.AddFileVersionToPath(hrefValue);
}
builder
.AppendHtml(hrefName)
.AppendHtml("=\"")
.Append(hrefValue)
.AppendHtml("\" ");
}
private enum Mode
{
/// <summary>
/// Just adding a file version for the generated urls.
/// </summary>
AppendVersion = 0,
/// <summary>
/// Just performing file globbing search for the href, rendering a separate <link> for each match.
/// </summary>
GlobbedHref = 1,
/// <summary>
/// Rendering a fallback block if primary stylesheet fails to load. Will also do globbing for both the
/// primary and fallback hrefs if the appropriate properties are set.
/// </summary>
Fallback = 2,
}
}
}