Browse Source

Soft enable CA1810 (#33659)

A lot of the warnings for this rule appear from logging. Given this is going
to be replaced by a source generator, this change soft enables the rule while
fixing warnings that appear in non-logging code

Contributes to #24055
Pranav K 4 years ago
parent
commit
78ab4bd673
63 changed files with 213 additions and 253 deletions
  1. 23 5
      .editorconfig
  2. 3 3
      src/Components/Web/src/Forms/InputNumber.cs
  3. 1 9
      src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs
  4. 4 9
      src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs
  5. 2 9
      src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs
  6. 2 2
      src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs
  7. 3 3
      src/DataProtection/DataProtection/src/KeyManagement/KeyManagementOptions.cs
  8. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs
  9. 1 1
      src/DataProtection/DataProtection/src/TypeForwardingActivator.cs
  10. 1 1
      src/DataProtection/DataProtection/src/XmlEncryption/XmlKeyDecryptionOptions.cs
  11. 1 1
      src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs
  12. 1 1
      src/Hosting/Hosting/src/Internal/ApplicationLifetime.cs
  13. 1 1
      src/Hosting/Hosting/src/Internal/HostingApplication.cs
  14. 1 1
      src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs
  15. 1 1
      src/Hosting/Hosting/src/Internal/WebHost.cs
  16. 1 1
      src/Hosting/Hosting/src/Internal/WebHostOptions.cs
  17. 2 2
      src/Hosting/Hosting/src/WebHostBuilder.cs
  18. 4 4
      src/Http/Headers/src/ContentDispositionHeaderValue.cs
  19. 4 4
      src/Http/Http/src/Features/FormFeature.cs
  20. 1 1
      src/Http/Routing/src/DefaultParameterPolicyFactory.cs
  21. 2 2
      src/Http/Routing/src/Matching/DfaMatcher.cs
  22. 1 1
      src/Http/Routing/src/Matching/EndpointComparer.cs
  23. 2 2
      src/Http/Routing/src/Matching/HostMatcherPolicy.cs
  24. 2 2
      src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs
  25. 1 1
      src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs
  26. 1 1
      src/Http/Routing/src/RouteCollection.cs
  27. 1 1
      src/Http/Routing/src/RouteValuesAddressScheme.cs
  28. 2 2
      src/Http/WebUtilities/src/BufferedReadStream.cs
  29. 1 1
      src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesOptions.cs
  30. 3 3
      src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
  31. 3 3
      src/Middleware/ResponseCaching/src/FastGuid.cs
  32. 24 22
      src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs
  33. 1 6
      src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs
  34. 5 10
      src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs
  35. 1 1
      src/Mvc/test/Mvc.FunctionalTests/AsyncEnumerableTestBase.cs
  36. 1 1
      src/ObjectPool/src/DisposableObjectPool.cs
  37. 1 1
      src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs
  38. 2 8
      src/Security/Authentication/Cookies/src/LoggingExtensions.cs
  39. 6 13
      src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs
  40. 8 13
      src/Security/Authorization/Core/src/LoggingExtensions.cs
  41. 1 8
      src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs
  42. 1 1
      src/Servers/IIS/IISIntegration/src/IISMiddleware.cs
  43. 7 5
      src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs
  44. 2 2
      src/Servers/Kestrel/Core/src/Internal/Http/Http1ChunkedEncodingMessageBody.cs
  45. 1 1
      src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs
  46. 2 2
      src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs
  47. 2 2
      src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs
  48. 1 1
      src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs
  49. 1 1
      src/Shared/CommandLineUtils/CommandLine/CommandOption.cs
  50. 1 1
      src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs
  51. 1 1
      src/Shared/SignalR/InProcessTestServer.cs
  52. 2 2
      src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs
  53. 4 11
      src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs
  54. 3 3
      src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsMessageParser.cs
  55. 1 1
      src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs
  56. 12 12
      src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs
  57. 7 5
      src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs
  58. 10 10
      src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocolWorker.cs
  59. 13 13
      src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs
  60. 7 9
      src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs
  61. 1 1
      src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs
  62. 6 6
      src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs
  63. 1 1
      src/SignalR/server/Core/src/Internal/HubFilterFactory.cs

+ 23 - 5
.editorconfig

@@ -91,13 +91,19 @@ dotnet_diagnostic.CA1802.severity = warning
 # CA1805: Do not initialize unnecessarily
 dotnet_diagnostic.CA1805.severity = warning
 
-# CA1823: Remove empty Finalizers
+# CA1810: Do not initialize unnecessarily
+dotnet_diagnostic.CA1810.severity = suggestion
+
+# CA1821: Remove empty Finalizers
 dotnet_diagnostic.CA1821.severity = warning
 
+# CA1822: Make member static
+dotnet_diagnostic.CA1822.severity = suggestion
+
 # CA1823: Avoid unused private fields
 dotnet_diagnostic.CA1823.severity = warning
 
-# CA1823: Avoid zero-length array allocations
+# CA1825: Avoid zero-length array allocations
 dotnet_diagnostic.CA1825.severity = warning
 
 # CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
@@ -185,9 +191,21 @@ dotnet_diagnostic.CA2200.severity = warning
 # CA2208: Instantiate argument exceptions correctly
 dotnet_diagnostic.CA2208.severity = warning
 
-[**/HostFactoryResolver.cs]
-# CA1823: Use literals where appropriate
-dotnet_diagnostic.CA1802.severity = suggestion
+# IDE0035: Remove unreachable code
+dotnet_diagnostic.IDE0035.severity = warning
+
+# IDE0036: Order modifiers
+dotnet_diagnostic.IDE0036.severity = warning
+
+# IDE0043: Format string contains invalid placeholder
+dotnet_diagnostic.IDE0043.severity = warning
+
+# IDE0044: Make field readonly
+dotnet_diagnostic.IDE0044.severity = warning
+
+# IDE0073: File header
+dotnet_diagnostic.IDE0073.severity = warning
+file_header_template = Copyright (c) .NET Foundation. All rights reserved.\nLicensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 [**/{test,samples,perf}/**.{cs,vb}]
 # CA1018: Mark attributes with AttributeUsageAttribute

+ 3 - 3
src/Components/Web/src/Forms/InputNumber.cs

@@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Components.Forms
     /// </summary>
     public class InputNumber<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase<TValue>
     {
-        private readonly static string _stepAttributeValue; // Null by default, so only allows whole numbers as per HTML spec
+        private static readonly string _stepAttributeValue = GetStepAttributeValue();
 
-        static InputNumber()
+        private static string GetStepAttributeValue()
         {
             // Unwrap Nullable<T>, because InputBase already deals with the Nullable aspect
             // of it for us. We will only get asked to parse the T for nonempty inputs.
@@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Components.Forms
                 targetType == typeof(double) ||
                 targetType == typeof(decimal))
             {
-                _stepAttributeValue = "any";
+                return "any";
             }
             else
             {

+ 1 - 9
src/Components/WebAssembly/WebAssembly/src/Rendering/RendererRegistry.cs

@@ -13,16 +13,8 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering
         // as well as rooting them for GC purposes, since nothing would otherwise be referencing
         // them even though we might still receive incoming events from JS.
 
+        private static readonly Dictionary<int, WebAssemblyRenderer>? _renderers = OperatingSystem.IsBrowser() ? new() : null;
         private static int _nextId;
-        private static Dictionary<int, WebAssemblyRenderer>? _renderers;
-
-        static RendererRegistry()
-        {
-            if (OperatingSystem.IsBrowser())
-            {
-                _renderers = new Dictionary<int, WebAssemblyRenderer>();
-            }
-        }
 
         internal static WebAssemblyRenderer Find(int rendererId)
         {

+ 4 - 9
src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs

@@ -163,21 +163,16 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering
 
         private static class Log
         {
-            private static readonly Action<ILogger, string, Exception> _unhandledExceptionRenderingComponent;
+            private static readonly Action<ILogger, string, Exception> _unhandledExceptionRenderingComponent = LoggerMessage.Define<string>(
+                LogLevel.Critical,
+                EventIds.UnhandledExceptionRenderingComponent,
+                "Unhandled exception rendering component: {Message}");
 
             private static class EventIds
             {
                 public static readonly EventId UnhandledExceptionRenderingComponent = new EventId(100, "ExceptionRenderingComponent");
             }
 
-            static Log()
-            {
-                _unhandledExceptionRenderingComponent = LoggerMessage.Define<string>(
-                    LogLevel.Critical,
-                    EventIds.UnhandledExceptionRenderingComponent,
-                    "Unhandled exception rendering component: {Message}");
-            }
-
             public static void UnhandledExceptionRenderingComponent(ILogger logger, Exception exception)
             {
                 _unhandledExceptionRenderingComponent(

+ 2 - 9
src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs

@@ -13,20 +13,13 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Services
     internal class WebAssemblyConsoleLogger<T> : ILogger<T>, ILogger
     {
         private const string _loglevelPadding = ": ";
-        private static readonly string _messagePadding;
-        private static readonly string _newLineWithMessagePadding;
+        private static readonly string _messagePadding = new(' ', GetLogLevelString(LogLevel.Information).Length + _loglevelPadding.Length);
+        private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding;
         private static readonly StringBuilder _logBuilder = new StringBuilder();
 
         private readonly string _name;
         private readonly WebAssemblyJSRuntime _jsRuntime;
 
-        static WebAssemblyConsoleLogger()
-        {
-            var logLevelString = GetLogLevelString(LogLevel.Information);
-            _messagePadding = new string(' ', logLevelString.Length + _loglevelPadding.Length);
-            _newLineWithMessagePadding = Environment.NewLine + _messagePadding;
-        }
-
         public WebAssemblyConsoleLogger(IJSRuntime jsRuntime)
             : this(string.Empty, (WebAssemblyJSRuntime)jsRuntime) // Cast for DI
         {

+ 2 - 2
src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs

@@ -47,8 +47,8 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
         public DefaultKeyResolver(IOptions<KeyManagementOptions> keyManagementOptions, ILoggerFactory loggerFactory)
         {
-            _keyPropagationWindow = keyManagementOptions.Value.KeyPropagationWindow;
-            _maxServerToServerClockSkew = keyManagementOptions.Value.MaxServerClockSkew;
+            _keyPropagationWindow = KeyManagementOptions.KeyPropagationWindow;
+            _maxServerToServerClockSkew = KeyManagementOptions.MaxServerClockSkew;
             _logger = loggerFactory.CreateLogger<DefaultKeyResolver>();
         }
 

+ 3 - 3
src/DataProtection/DataProtection/src/KeyManagement/KeyManagementOptions.cs

@@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// <remarks>
         /// This value is currently fixed at 48 hours.
         /// </remarks>
-        internal TimeSpan KeyPropagationWindow
+        internal static TimeSpan KeyPropagationWindow
         {
             get
             {
@@ -89,7 +89,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// <remarks>
         /// This value is currently fixed at 24 hours.
         /// </remarks>
-        internal TimeSpan KeyRingRefreshPeriod
+        internal static TimeSpan KeyRingRefreshPeriod
         {
             get
             {
@@ -109,7 +109,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
         /// <remarks>
         /// This value is currently fixed at 5 minutes.
         /// </remarks>
-        internal TimeSpan MaxServerClockSkew
+        internal static TimeSpan MaxServerClockSkew
         {
             get
             {

+ 1 - 1
src/DataProtection/DataProtection/src/KeyManagement/KeyRingProvider.cs

@@ -128,7 +128,7 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 
             _logger.UsingKeyAsDefaultKey(defaultKey.KeyId);
 
-            var nextAutoRefreshTime = now + GetRefreshPeriodWithJitter(_keyManagementOptions.KeyRingRefreshPeriod);
+            var nextAutoRefreshTime = now + GetRefreshPeriodWithJitter(KeyManagementOptions.KeyRingRefreshPeriod);
 
             // The cached keyring should expire at the earliest of (default key expiration, next auto-refresh time).
             // Since the refresh period and safety window are not user-settable, we can guarantee that there's at

+ 1 - 1
src/DataProtection/DataProtection/src/TypeForwardingActivator.cs

@@ -61,7 +61,7 @@ namespace Microsoft.AspNetCore.DataProtection
             return base.CreateInstance(expectedBaseType, originalTypeName);
         }
 
-        protected string RemoveVersionFromAssemblyName(string forwardedTypeName)
+        protected static string RemoveVersionFromAssemblyName(string forwardedTypeName)
         {
             // Type, Assembly, Version={Version}, Culture={Culture}, PublicKeyToken={Token}
 

+ 1 - 1
src/DataProtection/DataProtection/src/XmlEncryption/XmlKeyDecryptionOptions.cs

@@ -35,6 +35,6 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
             certificates.Add(certificate);
         }
 
-        private string GetKey(X509Certificate2 cert) => cert.Thumbprint;
+        private static string GetKey(X509Certificate2 cert) => cert.Thumbprint;
     }
 }

+ 1 - 1
src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs

@@ -351,7 +351,7 @@ namespace Microsoft.AspNetCore.Hosting
             return this;
         }
 
-        private WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
+        private static WebHostBuilderContext GetWebHostBuilderContext(HostBuilderContext context)
         {
             if (!context.Properties.TryGetValue(typeof(WebHostBuilderContext), out var contextVal))
             {

+ 1 - 1
src/Hosting/Hosting/src/Internal/ApplicationLifetime.cs

@@ -101,7 +101,7 @@ namespace Microsoft.AspNetCore.Hosting
             }
         }
 
-        private void ExecuteHandlers(CancellationTokenSource cancel)
+        private static void ExecuteHandlers(CancellationTokenSource cancel)
         {
             // Noop if this is already cancelled
             if (cancel.IsCancellationRequested)

+ 1 - 1
src/Hosting/Hosting/src/Internal/HostingApplication.cs

@@ -111,7 +111,7 @@ namespace Microsoft.AspNetCore.Hosting
                 _httpContextFactory!.Dispose(httpContext);
             }
 
-            _diagnostics.ContextDisposed(context);
+            HostingApplicationDiagnostics.ContextDisposed(context);
 
             // Reset the context as it may be pooled
             context.Reset();

+ 1 - 1
src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs

@@ -176,7 +176,7 @@ namespace Microsoft.AspNetCore.Hosting
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void ContextDisposed(HostingApplication.Context context)
+        public static void ContextDisposed(HostingApplication.Context context)
         {
             if (context.EventLogEnabled)
             {

+ 1 - 1
src/Hosting/Hosting/src/Internal/WebHost.cs

@@ -356,7 +356,7 @@ namespace Microsoft.AspNetCore.Hosting
             await DisposeServiceProviderAsync(_hostingServiceProvider).ConfigureAwait(false);
         }
 
-        private async ValueTask DisposeServiceProviderAsync(IServiceProvider? serviceProvider)
+        private static async ValueTask DisposeServiceProviderAsync(IServiceProvider? serviceProvider)
         {
             switch (serviceProvider)
             {

+ 1 - 1
src/Hosting/Hosting/src/Internal/WebHostOptions.cs

@@ -69,7 +69,7 @@ namespace Microsoft.AspNetCore.Hosting
             return HostingStartupAssemblies.Except(HostingStartupExcludeAssemblies, StringComparer.OrdinalIgnoreCase);
         }
 
-        private IReadOnlyList<string> Split(string value)
+        private static IReadOnlyList<string> Split(string value)
         {
             return value?.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
                 ?? Array.Empty<string>();

+ 2 - 2
src/Hosting/Hosting/src/WebHostBuilder.cs

@@ -338,7 +338,7 @@ namespace Microsoft.AspNetCore.Hosting
             return services;
         }
 
-        private void AddApplicationServices(IServiceCollection services, IServiceProvider hostingServiceProvider)
+        private static void AddApplicationServices(IServiceCollection services, IServiceProvider hostingServiceProvider)
         {
             // We are forwarding services from hosting container so hosting container
             // can still manage their lifetime (disposal) shared instances with application services.
@@ -352,7 +352,7 @@ namespace Microsoft.AspNetCore.Hosting
             services.Replace(ServiceDescriptor.Singleton(typeof(ActivitySource), activitySource!));
         }
 
-        private string ResolveContentRootPath(string contentRootPath, string basePath)
+        private static string ResolveContentRootPath(string contentRootPath, string basePath)
         {
             if (string.IsNullOrEmpty(contentRootPath))
             {

+ 4 - 4
src/Http/Headers/src/ContentDispositionHeaderValue.cs

@@ -518,7 +518,7 @@ namespace Microsoft.Net.Http.Headers
         }
 
         // Returns true if the value starts and ends with a quote
-        private bool IsQuoted(StringSegment value)
+        private static bool IsQuoted(StringSegment value)
         {
             Contract.Assert(value != null);
 
@@ -527,7 +527,7 @@ namespace Microsoft.Net.Http.Headers
         }
 
         // tspecials are required to be in a quoted string.  Only non-ascii needs to be encoded.
-        private bool RequiresEncoding(StringSegment input)
+        private static bool RequiresEncoding(StringSegment input)
         {
             Contract.Assert(input != null);
 
@@ -607,7 +607,7 @@ namespace Microsoft.Net.Http.Headers
 
         // Encode a string using RFC 5987 encoding
         // encoding'lang'PercentEncodedSpecials
-        private string Encode5987(StringSegment input)
+        private static string Encode5987(StringSegment input)
         {
             var builder = new StringBuilder("UTF-8\'\'");
             for (int i = 0; i < input.Length; i++)
@@ -649,7 +649,7 @@ namespace Microsoft.Net.Http.Headers
 
         // Attempt to decode using RFC 5987 encoding.
         // encoding'language'my%20string
-        private bool TryDecode5987(StringSegment input, [NotNullWhen(true)] out string? output)
+        private static bool TryDecode5987(StringSegment input, [NotNullWhen(true)] out string? output)
         {
             output = null;
 

+ 4 - 4
src/Http/Http/src/Features/FormFeature.cs

@@ -305,26 +305,26 @@ namespace Microsoft.AspNetCore.Http.Features
             return encoding;
         }
 
-        private bool HasApplicationFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
+        private static bool HasApplicationFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
         {
             // Content-Type: application/x-www-form-urlencoded; charset=utf-8
             return contentType != null && contentType.MediaType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase);
         }
 
-        private bool HasMultipartFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
+        private static bool HasMultipartFormContentType([NotNullWhen(true)] MediaTypeHeaderValue? contentType)
         {
             // Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymx2fSWqWSd0OxQqq
             return contentType != null && contentType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase);
         }
 
-        private bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
+        private static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition)
         {
             // Content-Disposition: form-data; name="key";
             return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")
                 && StringSegment.IsNullOrEmpty(contentDisposition.FileName) && StringSegment.IsNullOrEmpty(contentDisposition.FileNameStar);
         }
 
-        private bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
+        private static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition)
         {
             // Content-Disposition: form-data; name="myfile1"; filename="Misc 002.jpg"
             return contentDisposition != null && contentDisposition.DispositionType.Equals("form-data")

+ 1 - 1
src/Http/Routing/src/DefaultParameterPolicyFactory.cs

@@ -65,7 +65,7 @@ namespace Microsoft.AspNetCore.Routing
             return parameterPolicy;
         }
 
-        private IParameterPolicy InitializeRouteConstraint(
+        private static IParameterPolicy InitializeRouteConstraint(
             bool optional,
             IRouteConstraint routeConstraint)
         {

+ 2 - 2
src/Http/Routing/src/Matching/DfaMatcher.cs

@@ -222,7 +222,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             return (states[destination].Candidates, states[destination].Policies);
         }
 
-        private void ProcessCaptures(
+        private static void ProcessCaptures(
             KeyValuePair<string, object?>[] slots,
             (string parameterName, int segmentIndex, int slotIndex)[] captures,
             string path,
@@ -245,7 +245,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             }
         }
 
-        private void ProcessCatchAll(
+        private static void ProcessCatchAll(
             KeyValuePair<string, object?>[] slots,
             in (string parameterName, int segmentIndex, int slotIndex) catchAll,
             string path,

+ 1 - 1
src/Http/Routing/src/Matching/EndpointComparer.cs

@@ -51,7 +51,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             return compare == 0 ? ComparePattern(x, y) : compare;
         }
 
-        private int ComparePattern(Endpoint x, Endpoint y)
+        private static int ComparePattern(Endpoint x, Endpoint y)
         {
             // A RouteEndpoint always comes before a non-RouteEndpoint, regardless of its RawText value
             var routeEndpointX = x as RouteEndpoint;

+ 2 - 2
src/Http/Routing/src/Matching/HostMatcherPolicy.cs

@@ -49,7 +49,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             return applies;
         }
 
-        private bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
+        private static bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
         {
             return endpoints.Any(e =>
             {
@@ -296,7 +296,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             return new HostPolicyJumpTable(exitDestination, ordered);
         }
 
-        private int GetScore(in EdgeKey key)
+        private static int GetScore(in EdgeKey key)
         {
             // Higher score == lower priority.
             if (key.MatchesHost && !key.HasHostWildcard && key.MatchesPort)

+ 2 - 2
src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs

@@ -66,7 +66,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             return ContainsDynamicEndpoints(endpoints);
         }
 
-        private bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
+        private static bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
         {
             for (var i = 0; i < endpoints.Count; i++)
             {
@@ -402,7 +402,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
             }
         }
 
-        private Endpoint CreateRejectionEndpoint(IEnumerable<string> httpMethods)
+        private static Endpoint CreateRejectionEndpoint(IEnumerable<string> httpMethods)
         {
             var allow = string.Join(", ", httpMethods);
             return new Endpoint(

+ 1 - 1
src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs

@@ -217,7 +217,7 @@ namespace Microsoft.AspNetCore.Routing.Patterns
             return true;
         }
 
-        private void RemoveParameterDefault(List<RoutePatternPathSegment> segments, List<RoutePatternParameterPart> parameters, RoutePatternParameterPart parameter)
+        private static void RemoveParameterDefault(List<RoutePatternPathSegment> segments, List<RoutePatternParameterPart> parameters, RoutePatternParameterPart parameter)
         {
             // We know that a parameter can only appear once, so we only need to rewrite one segment and one parameter.
             for (var i = 0; i < segments.Count; i++)

+ 1 - 1
src/Http/Routing/src/RouteCollection.cs

@@ -131,7 +131,7 @@ namespace Microsoft.AspNetCore.Routing
             }
         }
 
-        private VirtualPathData? GetVirtualPath(VirtualPathContext context, List<IRouter> routes)
+        private static VirtualPathData? GetVirtualPath(VirtualPathContext context, List<IRouter> routes)
         {
             for (var i = 0; i < routes.Count; i++)
             {

+ 1 - 1
src/Http/Routing/src/RouteValuesAddressScheme.cs

@@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Routing
                 namedOutboundMatchResults);
         }
 
-        private OutboundRouteEntry CreateOutboundRouteEntry(
+        private static OutboundRouteEntry CreateOutboundRouteEntry(
             RouteEndpoint endpoint,
             IReadOnlyDictionary<string, object?> requiredValues,
             string? routeName)

+ 2 - 2
src/Http/WebUtilities/src/BufferedReadStream.cs

@@ -408,7 +408,7 @@ namespace Microsoft.AspNetCore.WebUtilities
             foundCR = b == CR;
         }
 
-        private string DecodeLine(MemoryStream builder, bool foundCRLF)
+        private static string DecodeLine(MemoryStream builder, bool foundCRLF)
         {
             // Drop the final CRLF, if any
             var length = foundCRLF ? builder.Length - 2 : builder.Length;
@@ -423,7 +423,7 @@ namespace Microsoft.AspNetCore.WebUtilities
             }
         }
 
-        private void ValidateBuffer(byte[] buffer, int offset, int count)
+        private static void ValidateBuffer(byte[] buffer, int offset, int count)
         {
             // Delegate most of our validation.
             var ignored = new ArraySegment<byte>(buffer, offset, count);

+ 1 - 1
src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesOptions.cs

@@ -33,7 +33,7 @@ namespace Microsoft.AspNetCore.Builder
             };
         }
 
-        private string BuildResponseBody(int httpStatusCode)
+        private static string BuildResponseBody(int httpStatusCode)
         {
             // Note the 500 spaces are to work around an IE 'feature'
             var internetExplorerWorkaround = new string(' ', 500);

+ 3 - 3
src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs

@@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.HttpOverrides
             _allowedHosts = allowedHosts;
         }
 
-        private bool IsTopLevelWildcard(string host)
+        private static bool IsTopLevelWildcard(string host)
         {
             return (string.Equals("*", host, StringComparison.Ordinal) // HttpSys wildcard
                            || string.Equals("[::]", host, StringComparison.Ordinal) // Kestrel wildcard, IPv6 Any
@@ -397,7 +397,7 @@ namespace Microsoft.AspNetCore.HttpOverrides
 
         // Empty was checked for by the caller
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private bool TryValidateScheme(string scheme)
+        private static bool TryValidateScheme(string scheme)
         {
             for (var i = 0; i < scheme.Length; i++)
             {
@@ -501,7 +501,7 @@ namespace Microsoft.AspNetCore.HttpOverrides
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private bool IsNumeric(char ch)
+        private static bool IsNumeric(char ch)
         {
             return '0' <= ch && ch <= '9';
         }

+ 3 - 3
src/Middleware/ResponseCaching/src/FastGuid.cs

@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
         // Base32 encoding - in ascii sort order for easy text based sorting
         private static readonly char[] s_encode32Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUV".ToCharArray();
         // Global ID
-        private static long NextId;
+        private static long NextId = InitializeNextId();
 
         // Instance components
         private string? _idString;
@@ -31,12 +31,12 @@ namespace Microsoft.AspNetCore.ResponseCaching
         }
 
         // Static constructor to initialize global components
-        static FastGuid()
+        private static long InitializeNextId()
         {
             var guidBytes = Guid.NewGuid().ToByteArray();
 
             // Use the first 4 bytes from the Guid to initialize global ID
-            NextId =
+            return
                 guidBytes[0] << 32 |
                 guidBytes[1] << 40 |
                 guidBytes[2] << 48 |

+ 24 - 22
src/Mvc/Mvc.Core/src/Formatters/HttpTokenParsingRules.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
 {
     internal static class HttpTokenParsingRules
     {
-        private static readonly bool[] TokenChars;
+        private static readonly bool[] TokenChars = CreateTokenChars();
         private const int MaxNestedCount = 5;
 
         internal const char CR = '\r';
@@ -21,36 +21,38 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
         // iso-8859-1, Western European (ISO)
         internal static readonly Encoding DefaultHttpEncoding = Encoding.GetEncoding(28591);
 
-        static HttpTokenParsingRules()
+        private static bool[] CreateTokenChars()
         {
             // token = 1*<any CHAR except CTLs or separators>
             // CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
 
-            TokenChars = new bool[128]; // everything is false
+            var tokenChars = new bool[128]; // everything is false
 
-            for (int i = 33; i < 127; i++) // skip Space (32) & DEL (127)
+            for (var i = 33; i < 127; i++) // skip Space (32) & DEL (127)
             {
-                TokenChars[i] = true;
+                tokenChars[i] = true;
             }
 
             // remove separators: these are not valid token characters
-            TokenChars[(byte)'('] = false;
-            TokenChars[(byte)')'] = false;
-            TokenChars[(byte)'<'] = false;
-            TokenChars[(byte)'>'] = false;
-            TokenChars[(byte)'@'] = false;
-            TokenChars[(byte)','] = false;
-            TokenChars[(byte)';'] = false;
-            TokenChars[(byte)':'] = false;
-            TokenChars[(byte)'\\'] = false;
-            TokenChars[(byte)'"'] = false;
-            TokenChars[(byte)'/'] = false;
-            TokenChars[(byte)'['] = false;
-            TokenChars[(byte)']'] = false;
-            TokenChars[(byte)'?'] = false;
-            TokenChars[(byte)'='] = false;
-            TokenChars[(byte)'{'] = false;
-            TokenChars[(byte)'}'] = false;
+            tokenChars[(byte)'('] = false;
+            tokenChars[(byte)')'] = false;
+            tokenChars[(byte)'<'] = false;
+            tokenChars[(byte)'>'] = false;
+            tokenChars[(byte)'@'] = false;
+            tokenChars[(byte)','] = false;
+            tokenChars[(byte)';'] = false;
+            tokenChars[(byte)':'] = false;
+            tokenChars[(byte)'\\'] = false;
+            tokenChars[(byte)'"'] = false;
+            tokenChars[(byte)'/'] = false;
+            tokenChars[(byte)'['] = false;
+            tokenChars[(byte)']'] = false;
+            tokenChars[(byte)'?'] = false;
+            tokenChars[(byte)'='] = false;
+            tokenChars[(byte)'{'] = false;
+            tokenChars[(byte)'}'] = false;
+
+            return tokenChars;
         }
 
         internal static bool IsTokenChar(char character)

+ 1 - 6
src/Mvc/Mvc.NewtonsoftJson/src/JsonSerializerSettingsProvider.cs

@@ -17,12 +17,7 @@ namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
 
         // return shared resolver by default for perf so slow reflection logic is cached once
         // developers can set their own resolver after the settings are returned if desired
-        private static readonly DefaultContractResolver SharedContractResolver;
-
-        static JsonSerializerSettingsProvider()
-        {
-            SharedContractResolver = CreateContractResolver();
-        }
+        private static readonly DefaultContractResolver SharedContractResolver = CreateContractResolver();
 
         /// <summary>
         /// Creates default <see cref="JsonSerializerSettings"/>.

+ 5 - 10
src/Mvc/Mvc.TagHelpers/src/MvcTagHelpersLoggerExtensions.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// 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;
@@ -8,15 +8,10 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
 {
     internal static class MvcTagHelperLoggerExtensions
     {
-        private static readonly Action<ILogger, string, Exception> _distributedFormatterDeserializedFailed;
-
-        static MvcTagHelperLoggerExtensions()
-        {
-            _distributedFormatterDeserializedFailed = LoggerMessage.Define<string>(
-                LogLevel.Error,
-                new EventId(1, "DistributedFormatterDeserializationException"),
-                "Couldn't deserialize cached value for key {Key}.");
-        }
+        private static readonly Action<ILogger, string, Exception> _distributedFormatterDeserializedFailed = LoggerMessage.Define<string>(
+            LogLevel.Error,
+            new EventId(1, "DistributedFormatterDeserializationException"),
+            "Couldn't deserialize cached value for key {Key}.");
 
         public static void DistributedFormatterDeserializationException(this ILogger logger, string key, Exception exception)
         {

+ 1 - 1
src/Mvc/test/Mvc.FunctionalTests/AsyncEnumerableTestBase.cs

@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// 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;

+ 1 - 1
src/ObjectPool/src/DisposableObjectPool.cs

@@ -81,7 +81,7 @@ namespace Microsoft.Extensions.ObjectPool
             }
         }
 
-        private void DisposeItem(T? item)
+        private static void DisposeItem(T? item)
         {
             if (item is IDisposable disposable)
             {

+ 1 - 1
src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs

@@ -120,7 +120,7 @@ namespace Microsoft.AspNetCore.Authentication.Cookies
             }
         }
 
-        private AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal)
+        private static AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal)
         {
             var principal = replacedPrincipal ?? ticket.Principal;
             var newPrincipal = new ClaimsPrincipal();

+ 2 - 8
src/Security/Authentication/Cookies/src/LoggingExtensions.cs

@@ -7,20 +7,14 @@ namespace Microsoft.Extensions.Logging
 {
     internal static class LoggingExtensions
     {
-        private static Action<ILogger, string, Exception?> _authenticationSchemeSignedIn;
-        private static Action<ILogger, string, Exception?> _authenticationSchemeSignedOut;
-
-        static LoggingExtensions()
-        {
-            _authenticationSchemeSignedIn = LoggerMessage.Define<string>(
+        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeSignedIn = LoggerMessage.Define<string>(
                 eventId: new EventId(10, "AuthenticationSchemeSignedIn"),
                 logLevel: LogLevel.Information,
                 formatString: "AuthenticationScheme: {AuthenticationScheme} signed in.");
-            _authenticationSchemeSignedOut = LoggerMessage.Define<string>(
+        private static readonly Action<ILogger, string, Exception?> _authenticationSchemeSignedOut = LoggerMessage.Define<string>(
                 eventId: new EventId(11, "AuthenticationSchemeSignedOut"),
                 logLevel: LogLevel.Information,
                 formatString: "AuthenticationScheme: {AuthenticationScheme} signed out.");
-        }
 
         public static void AuthenticationSchemeSignedIn(this ILogger logger, string authenticationScheme)
         {

+ 6 - 13
src/Security/Authentication/JwtBearer/src/LoggingExtensions.cs

@@ -7,25 +7,18 @@ namespace Microsoft.Extensions.Logging
 {
     internal static class LoggingExtensions
     {
-        private static Action<ILogger, Exception> _tokenValidationFailed;
-        private static Action<ILogger, Exception?> _tokenValidationSucceeded;
-        private static Action<ILogger, Exception> _errorProcessingMessage;
-
-        static LoggingExtensions()
-        {
-            _tokenValidationFailed = LoggerMessage.Define(
-                eventId: new EventId(1, "TokenValidationFailed"),
-                logLevel: LogLevel.Information,
-                formatString: "Failed to validate the token.");
-            _tokenValidationSucceeded = LoggerMessage.Define(
+        private static readonly Action<ILogger, Exception> _tokenValidationFailed = LoggerMessage.Define(
+            eventId: new EventId(1, "TokenValidationFailed"),
+            logLevel: LogLevel.Information,
+            formatString: "Failed to validate the token.");
+        private static readonly Action<ILogger, Exception?> _tokenValidationSucceeded = LoggerMessage.Define(
                 eventId: new EventId(2, "TokenValidationSucceeded"),
                 logLevel: LogLevel.Debug,
                 formatString: "Successfully validated the token.");
-            _errorProcessingMessage = LoggerMessage.Define(
+        private static readonly Action<ILogger, Exception> _errorProcessingMessage = LoggerMessage.Define(
                 eventId: new EventId(3, "ProcessingMessageFailed"),
                 logLevel: LogLevel.Error,
                 formatString: "Exception occurred while processing message.");
-        }
 
         public static void TokenValidationFailed(this ILogger logger, Exception ex)
             => _tokenValidationFailed(logger, ex);

+ 8 - 13
src/Security/Authorization/Core/src/LoggingExtensions.cs

@@ -8,20 +8,15 @@ namespace Microsoft.Extensions.Logging
 {
     internal static class LoggingExtensions
     {
-        private static Action<ILogger, string, Exception?> _userAuthorizationFailed;
-        private static Action<ILogger, Exception?> _userAuthorizationSucceeded;
+        private static readonly Action<ILogger, string, Exception?> _userAuthorizationFailed = LoggerMessage.Define<string>(
+            eventId: new EventId(2, "UserAuthorizationFailed"),
+            logLevel: LogLevel.Information,
+            formatString: "Authorization failed. {0}");
 
-        static LoggingExtensions()
-        {
-            _userAuthorizationSucceeded = LoggerMessage.Define(
-                eventId: new EventId(1, "UserAuthorizationSucceeded"),
-                logLevel: LogLevel.Debug,
-                formatString: "Authorization was successful.");
-            _userAuthorizationFailed = LoggerMessage.Define<string>(
-                eventId: new EventId(2, "UserAuthorizationFailed"),
-                logLevel: LogLevel.Information,
-                formatString: "Authorization failed. {0}");
-        }
+        private static readonly Action<ILogger, Exception?> _userAuthorizationSucceeded = LoggerMessage.Define(
+            eventId: new EventId(1, "UserAuthorizationSucceeded"),
+            logLevel: LogLevel.Debug,
+            formatString: "Authorization was successful.");
 
         public static void UserAuthorizationSucceeded(this ILogger logger)
             => _userAuthorizationSucceeded(logger, null);

+ 1 - 8
src/Servers/HttpSys/src/NativeInterop/ComNetOS.cs

@@ -9,13 +9,6 @@ namespace Microsoft.AspNetCore.Server.HttpSys
     {
         // Windows is assumed based on HttpApi.Supported which is checked in the HttpSysListener constructor.
         // Minimum support for Windows 7 is assumed.
-        internal static readonly bool IsWin8orLater;
-
-        static ComNetOS()
-        {
-            var win8Version = new Version(6, 2);
-
-            IsWin8orLater = (Environment.OSVersion.Version >= win8Version);
-        }
+        internal static readonly bool IsWin8orLater = OperatingSystem.IsWindowsVersionAtLeast(6, 2);
     }
 }

+ 1 - 1
src/Servers/IIS/IISIntegration/src/IISMiddleware.cs

@@ -184,7 +184,7 @@ namespace Microsoft.AspNetCore.Server.IISIntegration
             await _next(httpContext);
         }
 
-        private WindowsPrincipal? GetUser(HttpContext context)
+        private static WindowsPrincipal? GetUser(HttpContext context)
         {
             var tokenHeader = context.Request.Headers[MSAspNetCoreWinAuthToken];
 

+ 7 - 5
src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs

@@ -11,18 +11,18 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS
     // Uses Windows Job Objects to ensure external processes are killed if the current process is terminated non-gracefully.
     internal static class ProcessTracker
     {
-        private static readonly IntPtr _jobHandle;
+        private static readonly IntPtr _jobHandle = IntiailizeProcessTracker();
 
-        static ProcessTracker()
+        private static IntPtr IntiailizeProcessTracker()
         {
             // Requires Win8 or later
             if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || Environment.OSVersion.Version < new Version(6, 2))
             {
-                return;
+                return IntPtr.Zero;
             }
 
             // Job name is optional but helps with diagnostics.  Job name must be unique if non-null.
-            _jobHandle = CreateJobObject(IntPtr.Zero, name: $"ProcessTracker{Environment.ProcessId}");
+            var jobHandle = CreateJobObject(IntPtr.Zero, name: $"ProcessTracker{Environment.ProcessId}");
 
             var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
             {
@@ -38,7 +38,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS
             {
                 Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
 
-                if (!SetInformationJobObject(_jobHandle, JobObjectInfoType.ExtendedLimitInformation,
+                if (!SetInformationJobObject(jobHandle, JobObjectInfoType.ExtendedLimitInformation,
                     extendedInfoPtr, (uint)length))
                 {
                     throw new Win32Exception();
@@ -48,6 +48,8 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS
             {
                 Marshal.FreeHGlobal(extendedInfoPtr);
             }
+
+            return jobHandle;
         }
 
         public static void Add(Process process)

+ 2 - 2
src/Servers/Kestrel/Core/src/Internal/Http/Http1ChunkedEncodingMessageBody.cs

@@ -474,7 +474,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
             }
         }
 
-        private int CalculateChunkSize(int extraHexDigit, int currentParsedSize)
+        private static int CalculateChunkSize(int extraHexDigit, int currentParsedSize)
         {
             try
             {
@@ -515,7 +515,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
             Complete
         };
 
-        private Pipe CreateRequestBodyPipe(Http1Connection context)
+        private static Pipe CreateRequestBodyPipe(Http1Connection context)
             => new Pipe(new PipeOptions
             (
                 pool: context.MemoryPool,

+ 1 - 1
src/Servers/Kestrel/Core/src/Internal/Http/HttpParser.cs

@@ -440,7 +440,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
             return invalidIndex;
         }
 
-        private bool IsTlsHandshake(ReadOnlySpan<byte> requestLine)
+        private static bool IsTlsHandshake(ReadOnlySpan<byte> requestLine)
         {
             const byte SslRecordTypeHandshake = (byte)0x16;
 

+ 2 - 2
src/Servers/Kestrel/Core/src/Internal/Http2/Http2Connection.cs

@@ -437,7 +437,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
             return false;
         }
 
-        private bool ParsePreface(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
+        private static bool ParsePreface(in ReadOnlySequence<byte> buffer, out SequencePosition consumed, out SequencePosition examined)
         {
             consumed = buffer.Start;
             examined = buffer.End;
@@ -1448,7 +1448,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
             }
         }
 
-        private PseudoHeaderFields GetPseudoHeaderField(ReadOnlySpan<byte> name)
+        private static PseudoHeaderFields GetPseudoHeaderField(ReadOnlySpan<byte> name)
         {
             if (name.IsEmpty || name[0] != (byte)':')
             {

+ 2 - 2
src/Servers/Kestrel/Core/src/Internal/Http3/Http3Stream.cs

@@ -286,7 +286,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3
             }
         }
 
-        private bool IsPseudoHeaderField(ReadOnlySpan<byte> name, out PseudoHeaderFields headerField)
+        private static bool IsPseudoHeaderField(ReadOnlySpan<byte> name, out PseudoHeaderFields headerField)
         {
             headerField = PseudoHeaderFields.None;
 
@@ -512,7 +512,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3
             }
         }
 
-        private Task ProcessUnknownFrameAsync()
+        private static Task ProcessUnknownFrameAsync()
         {
             // https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-9
             // Unknown frames must be explicitly ignored.

+ 1 - 1
src/Shared/CommandLineUtils/CommandLine/AnsiConsole.cs

@@ -36,7 +36,7 @@ namespace Microsoft.Extensions.CommandLineUtils
 
         public ConsoleColor OriginalForegroundColor { get; }
 
-        private void SetColor(ConsoleColor color)
+        private static void SetColor(ConsoleColor color)
         {
             Console.ForegroundColor = (ConsoleColor)(((int)Console.ForegroundColor & 0x08) | ((int)color & 0x07));
         }

+ 1 - 1
src/Shared/CommandLineUtils/CommandLine/CommandOption.cs

@@ -100,7 +100,7 @@ namespace Microsoft.Extensions.CommandLineUtils
             return HasValue() ? Values[0] : null;
         }
 
-        private bool IsEnglishLetter(char c)
+        private static bool IsEnglishLetter(char c)
         {
             return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
         }

+ 1 - 1
src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs

@@ -96,7 +96,7 @@ namespace Microsoft.Extensions.Internal
             }
         }
 
-        public bool IsReadOnly
+        public static bool IsReadOnly
         {
             get
             {

+ 1 - 1
src/Shared/SignalR/InProcessTestServer.cs

@@ -129,7 +129,7 @@ namespace Microsoft.AspNetCore.SignalR.Tests
             });
         }
 
-        private string RenderLogs(IList<LogRecord> logs)
+        private static string RenderLogs(IList<LogRecord> logs)
         {
             var builder = new StringBuilder();
             foreach (var log in logs)

+ 2 - 2
src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs

@@ -457,7 +457,7 @@ namespace Microsoft.AspNetCore.SignalR.Client
             Log.Started(_logger);
         }
 
-        private ValueTask CloseAsync(ConnectionContext connection)
+        private static ValueTask CloseAsync(ConnectionContext connection)
         {
             return connection.DisposeAsync();
         }
@@ -1544,7 +1544,7 @@ namespace Microsoft.AspNetCore.SignalR.Client
             }
         }
 
-        private IDisposable? CreateLinkedToken(CancellationToken token1, CancellationToken token2, out CancellationToken linkedToken)
+        private static IDisposable? CreateLinkedToken(CancellationToken token1, CancellationToken token2, out CancellationToken linkedToken)
         {
             if (!token1.CanBeCanceled)
             {

+ 4 - 11
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/Constants.cs

@@ -11,18 +11,11 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
 {
     internal static class Constants
     {
-#pragma warning disable CA1802
-        public static readonly string UserAgent = "User-Agent";
-#pragma warning restore CA1802
-        public static readonly string UserAgentHeader;
+        public static readonly string UserAgent = OperatingSystem.IsBrowser() ? "X-SignalR-User-Agent" : "User-Agent";
+        public static readonly string UserAgentHeader = GetUserAgentHeader();
 
-        static Constants()
+        private static string GetUserAgentHeader()
         {
-            if (OperatingSystem.IsBrowser())
-            {
-                UserAgent = "X-SignalR-User-Agent";
-            }
-
             var assemblyVersion = typeof(Constants)
                 .Assembly
                 .GetCustomAttributes<AssemblyInformationalVersionAttribute>()
@@ -33,7 +26,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
             var runtime = ".NET";
             var runtimeVersion = RuntimeInformation.FrameworkDescription;
 
-            UserAgentHeader = ConstructUserAgent(typeof(Constants).Assembly.GetName().Version!, assemblyVersion.InformationalVersion, GetOS(), runtime, runtimeVersion);
+            return ConstructUserAgent(typeof(Constants).Assembly.GetName().Version!, assemblyVersion.InformationalVersion, GetOS(), runtime, runtimeVersion);
         }
 
         private static string GetOS()

+ 3 - 3
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsMessageParser.cs

@@ -147,7 +147,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private ReadOnlySpan<byte> ConvertBufferToSpan(in ReadOnlySequence<byte> buffer)
+        private static ReadOnlySpan<byte> ConvertBufferToSpan(in ReadOnlySequence<byte> buffer)
         {
             if (buffer.IsSingleSegment)
             {
@@ -162,7 +162,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
             _data.Clear();
         }
 
-        private void EnsureStartsWithDataPrefix(ReadOnlySpan<byte> line)
+        private static void EnsureStartsWithDataPrefix(ReadOnlySpan<byte> line)
         {
             if (!line.StartsWith(DataPrefix))
             {
@@ -170,7 +170,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
             }
         }
 
-        private bool IsMessageEnd(ReadOnlySpan<byte> line)
+        private static bool IsMessageEnd(ReadOnlySpan<byte> line)
         {
             return line.Length == SseLineEnding.Length && line.SequenceEqual(SseLineEnding);
         }

+ 1 - 1
src/SignalR/common/Http.Connections/src/Internal/HttpConnectionDispatcher.cs

@@ -339,7 +339,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Internal
             }
         }
 
-        private void WriteNegotiatePayload(IBufferWriter<byte> writer, string? connectionId, string? connectionToken, HttpContext context, HttpConnectionDispatcherOptions options,
+        private static void WriteNegotiatePayload(IBufferWriter<byte> writer, string? connectionId, string? connectionToken, HttpContext context, HttpConnectionDispatcherOptions options,
             int clientProtocolVersion, string? error)
         {
             var response = new NegotiationResponse();

+ 12 - 12
src/SignalR/common/Protocols.Json/src/Protocol/JsonHubProtocol.cs

@@ -418,7 +418,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private Dictionary<string, string> ReadHeaders(ref Utf8JsonReader reader)
+        private static Dictionary<string, string> ReadHeaders(ref Utf8JsonReader reader)
         {
             var headers = new Dictionary<string, string>(StringComparer.Ordinal);
 
@@ -508,7 +508,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private void WriteHeaders(Utf8JsonWriter writer, HubInvocationMessage message)
+        private static void WriteHeaders(Utf8JsonWriter writer, HubInvocationMessage message)
         {
             if (message.Headers != null && message.Headers.Count > 0)
             {
@@ -542,7 +542,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private void WriteCancelInvocationMessage(CancelInvocationMessage message, Utf8JsonWriter writer)
+        private static void WriteCancelInvocationMessage(CancelInvocationMessage message, Utf8JsonWriter writer)
         {
             WriteInvocationId(message, writer);
         }
@@ -582,7 +582,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             WriteStreamIds(message.StreamIds, writer);
         }
 
-        private void WriteCloseMessage(CloseMessage message, Utf8JsonWriter writer)
+        private static void WriteCloseMessage(CloseMessage message, Utf8JsonWriter writer)
         {
             if (message.Error != null)
             {
@@ -612,7 +612,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.WriteEndArray();
         }
 
-        private void WriteStreamIds(string[]? streamIds, Utf8JsonWriter writer)
+        private static void WriteStreamIds(string[]? streamIds, Utf8JsonWriter writer)
         {
             if (streamIds == null)
             {
@@ -640,7 +640,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.WriteNumber(TypePropertyNameBytes, type);
         }
 
-        private HubMessage BindCancelInvocationMessage(string? invocationId)
+        private static HubMessage BindCancelInvocationMessage(string? invocationId)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -650,7 +650,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new CancelInvocationMessage(invocationId);
         }
 
-        private HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
+        private static HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -670,7 +670,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new CompletionMessage(invocationId, error, result: null, hasResult: false);
         }
 
-        private HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
+        private static HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -685,7 +685,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new StreamItemMessage(invocationId, item);
         }
 
-        private HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
+        private static HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -707,7 +707,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new StreamInvocationMessage(invocationId, target, arguments, streamIds);
         }
 
-        private HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
+        private static HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds)
         {
             if (string.IsNullOrEmpty(target))
             {
@@ -770,7 +770,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return arguments ?? Array.Empty<object>();
         }
 
-        private CloseMessage BindCloseMessage(string? error, bool allowReconnect)
+        private static CloseMessage BindCloseMessage(string? error, bool allowReconnect)
         {
             // An empty string is still an error
             if (error == null && !allowReconnect)
@@ -781,7 +781,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new CloseMessage(error, allowReconnect);
         }
 
-        private HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
+        private static HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
         {
             if (headers != null && message is HubInvocationMessage invocationMessage)
             {

+ 7 - 5
src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs

@@ -94,18 +94,20 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
 
             private static class Cache<T>
             {
-                public static readonly IMessagePackFormatter<T>? Formatter;
+                public static readonly IMessagePackFormatter<T>? Formatter = ResolveFormatter();
 
-                static Cache()
+                private static IMessagePackFormatter<T>? ResolveFormatter()
                 {
                     foreach (var resolver in Resolvers)
                     {
-                        Formatter = resolver.GetFormatter<T>();
-                        if (Formatter != null)
+                        var formatter = resolver.GetFormatter<T>();
+                        if (formatter != null)
                         {
-                            return;
+                            return formatter;
                         }
                     }
+
+                    return null;
                 }
             }
         }

+ 10 - 10
src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocolWorker.cs

@@ -265,7 +265,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
 
         protected abstract object DeserializeObject(ref MessagePackReader reader, Type type, string field);
 
-        private T ApplyHeaders<T>(IDictionary<string, string>? source, T destination) where T : HubInvocationMessage
+        private static T ApplyHeaders<T>(IDictionary<string, string>? source, T destination) where T : HubInvocationMessage
         {
             if (source != null && source.Count > 0)
             {
@@ -440,7 +440,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
 
         protected abstract void Serialize(ref MessagePackWriter writer, Type type, object value);
 
-        private void WriteStreamIds(string[]? streamIds, ref MessagePackWriter writer)
+        private static void WriteStreamIds(string[]? streamIds, ref MessagePackWriter writer)
         {
             if (streamIds != null)
             {
@@ -487,7 +487,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.Write(message.InvocationId);
         }
 
-        private void WriteCloseMessage(CloseMessage message, ref MessagePackWriter writer)
+        private static void WriteCloseMessage(CloseMessage message, ref MessagePackWriter writer)
         {
             writer.WriteArrayHeader(3);
             writer.Write(HubProtocolConstants.CloseMessageType);
@@ -503,13 +503,13 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.Write(message.AllowReconnect);
         }
 
-        private void WritePingMessage(PingMessage pingMessage, ref MessagePackWriter writer)
+        private static void WritePingMessage(PingMessage pingMessage, ref MessagePackWriter writer)
         {
             writer.WriteArrayHeader(1);
             writer.Write(HubProtocolConstants.PingMessageType);
         }
 
-        private void PackHeaders(IDictionary<string, string>? headers, ref MessagePackWriter writer)
+        private static void PackHeaders(IDictionary<string, string>? headers, ref MessagePackWriter writer)
         {
             if (headers != null)
             {
@@ -532,7 +532,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
         private string ReadInvocationId(ref MessagePackReader reader) =>
             ReadString(ref reader, "invocationId");
 
-        private bool ReadBoolean(ref MessagePackReader reader, string field)
+        private static bool ReadBoolean(ref MessagePackReader reader, string field)
         {
             try
             {
@@ -544,7 +544,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private int ReadInt32(ref MessagePackReader reader, string field)
+        private static int ReadInt32(ref MessagePackReader reader, string field)
         {
             try
             {
@@ -556,7 +556,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        protected string ReadString(ref MessagePackReader reader, string field)
+        protected static string ReadString(ref MessagePackReader reader, string field)
         {
             try
             {
@@ -568,7 +568,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private long ReadMapLength(ref MessagePackReader reader, string field)
+        private static long ReadMapLength(ref MessagePackReader reader, string field)
         {
             try
             {
@@ -581,7 +581,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
 
         }
 
-        private long ReadArrayLength(ref MessagePackReader reader, string field)
+        private static long ReadArrayLength(ref MessagePackReader reader, string field)
         {
             try
             {

+ 13 - 13
src/SignalR/common/Protocols.NewtonsoftJson/src/Protocol/NewtonsoftJsonHubProtocol.cs

@@ -416,7 +416,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private Dictionary<string, string> ReadHeaders(JsonTextReader reader)
+        private static Dictionary<string, string> ReadHeaders(JsonTextReader reader)
         {
             var headers = new Dictionary<string, string>(StringComparer.Ordinal);
 
@@ -506,7 +506,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private void WriteHeaders(JsonTextWriter writer, HubInvocationMessage message)
+        private static void WriteHeaders(JsonTextWriter writer, HubInvocationMessage message)
         {
             if (message.Headers != null && message.Headers.Count > 0)
             {
@@ -536,7 +536,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private void WriteCancelInvocationMessage(CancelInvocationMessage message, JsonTextWriter writer)
+        private static void WriteCancelInvocationMessage(CancelInvocationMessage message, JsonTextWriter writer)
         {
             WriteInvocationId(message, writer);
         }
@@ -570,7 +570,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             WriteStreamIds(message.StreamIds, writer);
         }
 
-        private void WriteCloseMessage(CloseMessage message, JsonTextWriter writer)
+        private static void WriteCloseMessage(CloseMessage message, JsonTextWriter writer)
         {
             if (message.Error != null)
             {
@@ -597,7 +597,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.WriteEndArray();
         }
 
-        private void WriteStreamIds(string[]? streamIds, JsonTextWriter writer)
+        private static void WriteStreamIds(string[]? streamIds, JsonTextWriter writer)
         {
             if (streamIds == null)
             {
@@ -628,7 +628,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             writer.WriteValue(type);
         }
 
-        private HubMessage BindCancelInvocationMessage(string? invocationId)
+        private static HubMessage BindCancelInvocationMessage(string? invocationId)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -638,7 +638,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new CancelInvocationMessage(invocationId);
         }
 
-        private HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
+        private static HubMessage BindCompletionMessage(string invocationId, string? error, object? result, bool hasResult, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -658,7 +658,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new CompletionMessage(invocationId, error, result: null, hasResult: false);
         }
 
-        private HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
+        private static HubMessage BindStreamItemMessage(string invocationId, object? item, bool hasItem, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -673,7 +673,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new StreamItemMessage(invocationId, item);
         }
 
-        private HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
+        private static HubMessage BindStreamInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(invocationId))
             {
@@ -695,7 +695,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new StreamInvocationMessage(invocationId, target, arguments, streamIds);
         }
 
-        private HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
+        private static HubMessage BindInvocationMessage(string? invocationId, string target, object?[]? arguments, bool hasArguments, string[]? streamIds, IInvocationBinder binder)
         {
             if (string.IsNullOrEmpty(target))
             {
@@ -712,7 +712,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             return new InvocationMessage(invocationId, target, arguments, streamIds);
         }
 
-        private bool ReadArgumentAsType(JsonTextReader reader, IReadOnlyList<Type> paramTypes, int paramIndex)
+        private static bool ReadArgumentAsType(JsonTextReader reader, IReadOnlyList<Type> paramTypes, int paramIndex)
         {
             if (paramIndex < paramTypes.Count)
             {
@@ -771,7 +771,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             throw new JsonReaderException("Unexpected end when reading JSON");
         }
 
-        private CloseMessage BindCloseMessage(string? error, bool allowReconnect)
+        private static CloseMessage BindCloseMessage(string? error, bool allowReconnect)
         {
             // An empty string is still an error
             if (error == null && !allowReconnect)
@@ -814,7 +814,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
             }
         }
 
-        private HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
+        private static HubMessage ApplyHeaders(HubMessage message, Dictionary<string, string>? headers)
         {
             if (headers != null && message is HubInvocationMessage invocationMessage)
             {

+ 7 - 9
src/SignalR/common/SignalR.Common/src/Protocol/HandshakeProtocol.cs

@@ -3,7 +3,6 @@
 
 using System;
 using System.Buffers;
-using System.Collections.Concurrent;
 using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.IO;
@@ -19,23 +18,22 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
     public static class HandshakeProtocol
     {
         private const string ProtocolPropertyName = "protocol";
-        private static JsonEncodedText ProtocolPropertyNameBytes = JsonEncodedText.Encode(ProtocolPropertyName);
+        private static readonly JsonEncodedText ProtocolPropertyNameBytes = JsonEncodedText.Encode(ProtocolPropertyName);
         private const string ProtocolVersionPropertyName = "version";
-        private static JsonEncodedText ProtocolVersionPropertyNameBytes = JsonEncodedText.Encode(ProtocolVersionPropertyName);
+        private static readonly JsonEncodedText ProtocolVersionPropertyNameBytes = JsonEncodedText.Encode(ProtocolVersionPropertyName);
         private const string ErrorPropertyName = "error";
-        private static JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName);
+        private static readonly JsonEncodedText ErrorPropertyNameBytes = JsonEncodedText.Encode(ErrorPropertyName);
         private const string TypePropertyName = "type";
-        private static JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName);
+        private static readonly JsonEncodedText TypePropertyNameBytes = JsonEncodedText.Encode(TypePropertyName);
+        private static readonly ReadOnlyMemory<byte> _successHandshakeData = GetSuccessHandshakeData();
 
-        private static readonly ReadOnlyMemory<byte> _successHandshakeData;
-
-        static HandshakeProtocol()
+        private static ReadOnlyMemory<byte> GetSuccessHandshakeData()
         {
             var memoryBufferWriter = MemoryBufferWriter.Get();
             try
             {
                 WriteResponseMessage(HandshakeResponseMessage.Empty, memoryBufferWriter);
-                _successHandshakeData = memoryBufferWriter.ToArray();
+                return memoryBufferWriter.ToArray();
             }
             finally
             {

+ 1 - 1
src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs

@@ -275,7 +275,7 @@ namespace Microsoft.AspNetCore.SignalR
             return new SerializedHubMessage(CreateInvocationMessage(methodName, args));
         }
 
-        private HubMessage CreateInvocationMessage(string methodName, object?[] args)
+        private static HubMessage CreateInvocationMessage(string methodName, object?[] args)
         {
             return new InvocationMessage(methodName, args);
         }

+ 6 - 6
src/SignalR/server/Core/src/Internal/DefaultHubDispatcher.cs

@@ -343,7 +343,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
                             catch (Exception ex)
                             {
                                 Log.FailedInvokingHubMethod(logger, hubMethodInvocationMessage.Target, ex);
-                                await dispatcher.SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
+                                await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                     ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, enableDetailedErrors));
                                 return;
                             }
@@ -353,7 +353,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
                                 // And normal invocations handle cleanup below in the finally
                                 if (isStreamCall)
                                 {
-                                    await dispatcher.CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
+                                    await CleanupInvocation(connection, hubMethodInvocationMessage, hubActivator, hub, scope);
                                 }
                             }
 
@@ -402,7 +402,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
             }
         }
 
-        private ValueTask CleanupInvocation(HubConnectionContext connection, HubMethodInvocationMessage hubMessage, IHubActivator<THub>? hubActivator,
+        private static ValueTask CleanupInvocation(HubConnectionContext connection, HubMethodInvocationMessage hubMessage, IHubActivator<THub>? hubActivator,
             THub? hub, AsyncServiceScope scope)
         {
             if (hubMessage.StreamIds != null)
@@ -513,7 +513,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
             return ExecuteMethod(methodExecutor, hub, arguments);
         }
 
-        private async ValueTask<object?> ExecuteMethod(ObjectMethodExecutor methodExecutor, Hub hub, object?[] arguments)
+        private static async ValueTask<object?> ExecuteMethod(ObjectMethodExecutor methodExecutor, Hub hub, object?[] arguments)
         {
             if (methodExecutor.IsMethodAsync)
             {
@@ -533,7 +533,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
             }
         }
 
-        private async Task SendInvocationError(string? invocationId,
+        private static async Task SendInvocationError(string? invocationId,
             HubConnectionContext connection, string errorMessage)
         {
             if (string.IsNullOrEmpty(invocationId))
@@ -551,7 +551,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
             hub.Groups = _hubContext.Groups;
         }
 
-        private Task<bool> IsHubMethodAuthorized(IServiceProvider provider, HubConnectionContext hubConnectionContext, HubMethodDescriptor descriptor, object?[] hubMethodArguments, Hub hub)
+        private static Task<bool> IsHubMethodAuthorized(IServiceProvider provider, HubConnectionContext hubConnectionContext, HubMethodDescriptor descriptor, object?[] hubMethodArguments, Hub hub)
         {
             // If there are no policies we don't need to run auth
             if (descriptor.Policies.Count == 0)

+ 1 - 1
src/SignalR/server/Core/src/Internal/HubFilterFactory.cs

@@ -72,7 +72,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal
             }
         }
 
-        private ValueTask DisposeFilter(IHubFilter filter)
+        private static ValueTask DisposeFilter(IHubFilter filter)
         {
             if (filter is IAsyncDisposable asyncDispsable)
             {