|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Collections.Concurrent; |
| 5 | +using System.Reflection; |
| 6 | +using System.Reflection.Metadata; |
| 7 | +using Microsoft.AspNetCore.Components.Endpoints; |
| 8 | +using Microsoft.AspNetCore.Components.Routing; |
| 9 | +using Microsoft.AspNetCore.Http; |
| 10 | + |
| 11 | +[assembly: MetadataUpdateHandler(typeof(RazorComponentsEndpointHttpContextExtensions.MetadataUpdateHandler))] |
| 12 | + |
| 13 | +namespace Microsoft.AspNetCore.Components.Routing; |
| 14 | + |
| 15 | +/// <summary> |
| 16 | +/// Extensions to <see cref="HttpContext"/> for Razor component applications. |
| 17 | +/// </summary> |
| 18 | +public static class RazorComponentsEndpointHttpContextExtensions |
| 19 | +{ |
| 20 | + private static readonly ConcurrentDictionary<Type, bool> AcceptsInteractiveRoutingCache = new(); |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Determines whether the current endpoint is a Razor component that can be reached through |
| 24 | + /// interactive routing. This is true for all page components except if they declare the |
| 25 | + /// attribute <see cref="ExcludeFromInteractiveRoutingAttribute"/>. |
| 26 | + /// </summary> |
| 27 | + /// <param name="context">The <see cref="HttpContext"/>.</param> |
| 28 | + /// <returns>True if the current endpoint is a Razor component that does not declare <see cref="ExcludeFromInteractiveRoutingAttribute"/>.</returns> |
| 29 | + public static bool AcceptsInteractiveRouting(this HttpContext context) |
| 30 | + { |
| 31 | + ArgumentNullException.ThrowIfNull(context); |
| 32 | + |
| 33 | + var pageType = context.GetEndpoint()?.Metadata.GetMetadata<ComponentTypeMetadata>()?.Type; |
| 34 | + |
| 35 | + return pageType is not null |
| 36 | + && AcceptsInteractiveRoutingCache.GetOrAdd( |
| 37 | + pageType, |
| 38 | + static pageType => !pageType.IsDefined(typeof(ExcludeFromInteractiveRoutingAttribute))); |
| 39 | + } |
| 40 | + |
| 41 | + internal static class MetadataUpdateHandler |
| 42 | + { |
| 43 | + /// <summary> |
| 44 | + /// Invoked as part of <see cref="MetadataUpdateHandlerAttribute" /> contract for hot reload. |
| 45 | + /// </summary> |
| 46 | + public static void ClearCache(Type[]? _) |
| 47 | + => AcceptsInteractiveRoutingCache.Clear(); |
| 48 | + } |
| 49 | +} |
0 commit comments