diff --git a/src/Shared/ResultsHelpers/SharedUrlHelper.cs b/src/Shared/ResultsHelpers/SharedUrlHelper.cs index aa64d071bfef..4b40110fd303 100644 --- a/src/Shared/ResultsHelpers/SharedUrlHelper.cs +++ b/src/Shared/ResultsHelpers/SharedUrlHelper.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Internal; @@ -32,49 +33,50 @@ internal static class SharedUrlHelper internal static bool IsLocalUrl([NotNullWhen(true)] string? url) { - if (string.IsNullOrEmpty(url)) + var urlSpan = url.AsSpan(); + + if (urlSpan.IsEmpty) { return false; } // Allows "/" or "/foo" but not "//" or "/\". - if (url[0] == '/') + if (urlSpan[0] == '/') { // url is exactly "/" - if (url.Length == 1) + if (urlSpan.Length < 2) { return true; } // url doesn't start with "//" or "/\" - if (url[1] != '/' && url[1] != '\\') + if (urlSpan[1] is not '/' and '\\') { - return !HasControlCharacter(url.AsSpan(1)); + return !HasControlCharacter(urlSpan.Slice(1)); } return false; } // Allows "~/" or "~/foo" but not "~//" or "~/\". - if (url[0] == '~' && url.Length > 1 && url[1] == '/') + if (urlSpan.StartsWith("~/")) { // url is exactly "~/" - if (url.Length == 2) + if (urlSpan.Length < 3) { return true; } // url doesn't start with "~//" or "~/\" - if (url[2] != '/' && url[2] != '\\') + if (urlSpan[2] is not '/' and '\\') { - return !HasControlCharacter(url.AsSpan(2)); + return !HasControlCharacter(urlSpan.Slice(2)); } - - return false; } return false; + [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool HasControlCharacter(ReadOnlySpan readOnlySpan) { // URLs may not contain ASCII control characters.