Kaynağa Gözat

Enable build time warnings for IDE code analysis rules (#34215)

* Enable build time warnings for IDE code analysis rules

* Enables build time warnings for readonly, modifier ordering and const
* Fixes all of the warnings

Contributes to https://github.com/dotnet/aspnetcore/issues/24055
Pranav K 4 yıl önce
ebeveyn
işleme
10beca5a98
100 değiştirilmiş dosya ile 195 ekleme ve 191 silme
  1. 2 1
      .editorconfig
  2. 3 0
      eng/targets/CSharp.Common.targets
  3. 1 1
      src/Analyzers/Analyzers/src/StartupAnalysis.cs
  4. 3 3
      src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
  5. 1 1
      src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs
  6. 2 2
      src/Caching/SqlServer/src/PlatformHelper.cs
  7. 1 1
      src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs
  8. 1 1
      src/Components/Components/src/CascadingParameterState.cs
  9. 1 1
      src/Components/Components/src/DynamicComponent.cs
  10. 1 1
      src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs
  11. 1 1
      src/Components/Components/src/RenderTree/EventArgsTypeCache.cs
  12. 3 3
      src/Components/Components/src/Rendering/RenderTreeBuilder.cs
  13. 1 1
      src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs
  14. 1 1
      src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs
  15. 2 2
      src/Components/Components/test/RendererTest.cs
  16. 2 2
      src/Components/Components/test/Routing/RouteTableFactoryTests.cs
  17. 1 1
      src/Components/Forms/src/ValidationStateChangedEventArgs.cs
  18. 1 1
      src/Components/Ignitor/src/NodeSerializer.cs
  19. 1 1
      src/Components/Server/test/Circuits/RemoteRendererTest.cs
  20. 1 1
      src/Components/Server/test/Circuits/RenderBatchWriterTest.cs
  21. 1 1
      src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs
  22. 1 1
      src/Components/Web/src/Forms/FieldCssClassProvider.cs
  23. 2 2
      src/Components/WebAssembly/Server/src/TargetPickerUi.cs
  24. 1 1
      src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs
  25. 1 1
      src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs
  26. 1 1
      src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs
  27. 1 1
      src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs
  28. 2 2
      src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs
  29. 1 1
      src/Components/WebView/WebView/src/StaticContentProvider.cs
  30. 2 2
      src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs
  31. 2 2
      src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs
  32. 1 1
      src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs
  33. 1 1
      src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs
  34. 1 1
      src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs
  35. 2 2
      src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs
  36. 1 1
      src/Components/test/testassets/TestServer/Controllers/UserController.cs
  37. 1 1
      src/Components/test/testassets/TestServer/ResourceRequestLog.cs
  38. 1 1
      src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs
  39. 1 1
      src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs
  40. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs
  41. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs
  42. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs
  43. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs
  44. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs
  45. 1 1
      src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs
  46. 1 1
      src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs
  47. 1 1
      src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
  48. 1 1
      src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs
  49. 1 1
      src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs
  50. 1 1
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs
  51. 1 1
      src/DataProtection/DataProtection/src/BitHelpers.cs
  52. 1 1
      src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs
  53. 1 1
      src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs
  54. 1 1
      src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs
  55. 1 1
      src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
  56. 1 1
      src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs
  57. 1 1
      src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs
  58. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs
  59. 1 1
      src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs
  60. 66 66
      src/DataProtection/DataProtection/src/LoggingExtensions.cs
  61. 1 1
      src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs
  62. 1 1
      src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs
  63. 1 1
      src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs
  64. 1 1
      src/DataProtection/DataProtection/src/MemoryProtection.cs
  65. 1 1
      src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs
  66. 1 1
      src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs
  67. 1 1
      src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs
  68. 1 1
      src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs
  69. 1 1
      src/DataProtection/DataProtection/src/Secret.cs
  70. 1 1
      src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs
  71. 2 2
      src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs
  72. 1 1
      src/Hosting/Hosting/src/Internal/HostingApplication.cs
  73. 1 1
      src/Hosting/Hosting/src/Startup/DelegateStartup.cs
  74. 1 1
      src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs
  75. 1 1
      src/Hosting/TestHost/src/ResponseBodyReaderStream.cs
  76. 1 1
      src/Hosting/TestHost/src/TestServer.cs
  77. 3 3
      src/Hosting/TestHost/src/TestWebSocket.cs
  78. 1 1
      src/Http/Headers/src/GenericHeaderParser.cs
  79. 1 1
      src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs
  80. 1 1
      src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs
  81. 1 1
      src/Http/Http.Abstractions/test/UseMiddlewareTest.cs
  82. 2 2
      src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs
  83. 1 1
      src/Http/Http.Extensions/src/QueryBuilder.cs
  84. 1 1
      src/Http/Http/src/Features/RequestBodyPipeFeature.cs
  85. 1 1
      src/Http/Http/src/Features/RequestCookiesFeature.cs
  86. 2 2
      src/Http/Http/src/FormCollection.cs
  87. 1 1
      src/Http/Http/src/HeaderDictionary.cs
  88. 1 1
      src/Http/Http/src/HttpContextAccessor.cs
  89. 3 3
      src/Http/Http/src/Internal/DefaultConnectionInfo.cs
  90. 6 6
      src/Http/Http/src/Internal/DefaultHttpRequest.cs
  91. 3 3
      src/Http/Http/src/Internal/DefaultWebSocketManager.cs
  92. 2 2
      src/Http/Http/src/Internal/ItemsDictionary.cs
  93. 1 1
      src/Http/Http/src/Internal/RequestCookieCollection.cs
  94. 1 1
      src/Http/Http/src/QueryCollection.cs
  95. 1 1
      src/Http/Http/src/QueryCollectionInternal.cs
  96. 1 1
      src/Http/Http/test/DefaultHttpContextTests.cs
  97. 1 1
      src/Http/Http/test/Features/NonSeekableReadStream.cs
  98. 1 1
      src/Http/Http/test/Internal/DefaultHttpResponseTests.cs
  99. 1 1
      src/Http/Owin/test/OwinExtensionTests.cs
  100. 1 1
      src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs

+ 2 - 1
.editorconfig

@@ -195,6 +195,7 @@ dotnet_diagnostic.CA2208.severity = warning
 dotnet_diagnostic.IDE0035.severity = warning
 
 # IDE0036: Order modifiers
+csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
 dotnet_diagnostic.IDE0036.severity = warning
 
 # IDE0043: Format string contains invalid placeholder
@@ -204,7 +205,7 @@ dotnet_diagnostic.IDE0043.severity = warning
 dotnet_diagnostic.IDE0044.severity = warning
 
 # IDE0073: File header
-dotnet_diagnostic.IDE0073.severity = warning
+dotnet_diagnostic.IDE0073.severity = suggestion
 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}]

+ 3 - 0
eng/targets/CSharp.Common.targets

@@ -27,6 +27,9 @@
         '$(ISBenchmarkProject)' == 'true' OR
         '$(IsSampleProject)' == 'true' OR
         '$(IsMicrobenchmarksProject)' == 'true'">$(NoWarn);CA1416</NoWarn>
+
+    <!-- Enable .NET code style analysis during build for src projects. -->
+    <EnforceCodeStyleInBuild Condition="'$(EnforceCodeStyleInBuild)' == ''">true</EnforceCodeStyleInBuild>
   </PropertyGroup>
 
   <ItemGroup Condition=" '$(DotNetBuildFromSource)' != 'true' AND $(AddPublicApiAnalyzers) ">

+ 1 - 1
src/Analyzers/Analyzers/src/StartupAnalysis.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Analyzers
 {
     internal class StartupAnalysis
     {
-        private ImmutableDictionary<INamedTypeSymbol, ImmutableArray<object>> _analysesByType;
+        private readonly ImmutableDictionary<INamedTypeSymbol, ImmutableArray<object>> _analysesByType;
 
         public StartupAnalysis(
             StartupSymbols startupSymbols,

+ 3 - 3
src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs

@@ -27,7 +27,7 @@ namespace Microsoft.AspNetCore.Analyzers
                 });
             }
 
-            internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor(
+            internal static readonly DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor(
                 "ASP0000",
                 "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'",
                 "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.",
@@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Analyzers
                 isEnabledByDefault: true,
                 helpLinkUri: "https://aka.ms/AA5k895");
 
-            internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor(
+            internal static readonly DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor(
                 "MVC1005",
                 "Cannot use UseMvc with Endpoint Routing.",
                 "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRouting = false' inside '{1}'.",
@@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Analyzers
                 isEnabledByDefault: true,
                 helpLinkUri: "https://aka.ms/YJggeFn");
 
-            internal readonly static DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor(
+            internal static readonly DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor(
                 "ASP0001",
                 "Authorization middleware is incorrectly configured.",
                 "The call to UseAuthorization should appear between app.UseRouting() and app.UseEndpoints(..) for authorization to be correctly evaluated.",

+ 1 - 1
src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Authentication.AzureADB2C.UI
     [Obsolete("This is obsolete and will be removed in a future version. Use Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.")]
     internal class AzureADB2COpenIDConnectEventHandlers
     {
-        private IDictionary<string, string> _policyToIssuerAddress =
+        private readonly IDictionary<string, string> _policyToIssuerAddress =
             new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 
         public AzureADB2COpenIDConnectEventHandlers(string schemeName, AzureADB2COptions options)

+ 2 - 2
src/Caching/SqlServer/src/PlatformHelper.cs

@@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Caching.SqlServer
 {
     internal static class PlatformHelper
     {
-        private static Lazy<bool> _isMono = new Lazy<bool>(() => Type.GetType("Mono.Runtime") != null);
+        private static readonly Lazy<bool> _isMono = new Lazy<bool>(() => Type.GetType("Mono.Runtime") != null);
 
         public static bool IsMono
         {
@@ -17,4 +17,4 @@ namespace Microsoft.Extensions.Caching.SqlServer
             }
         }
     }
-}
+}

+ 1 - 1
src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs

@@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Components.Analyzers.Tests.TestFiles.ComponentInt
 {
     /*MMBaseClass*/class UsesRendererTypesInDeclarations : Renderer
     {
-        private Renderer /*MMField*/_field = null;
+        private readonly Renderer /*MMField*/_field = null;
 
         public UsesRendererTypesInDeclarations()
             /*MMInvocation*/: base(null, null)

+ 1 - 1
src/Components/Components/src/CascadingParameterState.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components
 {
     internal readonly struct CascadingParameterState
     {
-        private readonly static ConcurrentDictionary<Type, ReflectedCascadingParameterInfo[]> _cachedInfos = new();
+        private static readonly ConcurrentDictionary<Type, ReflectedCascadingParameterInfo[]> _cachedInfos = new();
 
         public string LocalValueName { get; }
         public ICascadingValueComponent ValueSupplier { get; }

+ 1 - 1
src/Components/Components/src/DynamicComponent.cs

@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components
     public class DynamicComponent : IComponent
     {
         private RenderHandle _renderHandle;
-        private RenderFragment _cachedRenderFragment;
+        private readonly RenderFragment _cachedRenderFragment;
 
         /// <summary>
         /// Constructs an instance of <see cref="DynamicComponent"/>.

+ 1 - 1
src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs

@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components.Lifetime
     public class ComponentApplicationLifetime
     {
         private bool _stateIsPersisted;
-        private List<ComponentApplicationState.OnPersistingCallback> _pauseCallbacks = new();
+        private readonly List<ComponentApplicationState.OnPersistingCallback> _pauseCallbacks = new();
         private readonly Dictionary<string, byte[]> _currentState = new();
         private readonly ILogger<ComponentApplicationLifetime> _logger;
 

+ 1 - 1
src/Components/Components/src/RenderTree/EventArgsTypeCache.cs

@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Components.RenderTree
 {
     internal static class EventArgsTypeCache
     {
-        private static ConcurrentDictionary<MethodInfo, Type> Cache = new ConcurrentDictionary<MethodInfo, Type>();
+        private static readonly ConcurrentDictionary<MethodInfo, Type> Cache = new ConcurrentDictionary<MethodInfo, Type>();
 
         public static Type GetEventArgsType(MethodInfo methodInfo)
         {

+ 3 - 3
src/Components/Components/src/Rendering/RenderTreeBuilder.cs

@@ -20,9 +20,9 @@ namespace Microsoft.AspNetCore.Components.Rendering
     /// </summary>
     public sealed class RenderTreeBuilder : IDisposable
     {
-        private readonly static object BoxedTrue = true;
-        private readonly static object BoxedFalse = false;
-        private readonly static string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}";
+        private static readonly object BoxedTrue = true;
+        private static readonly object BoxedFalse = false;
+        private static readonly string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}";
 
         private readonly RenderTreeFrameArrayBuilder _entries = new RenderTreeFrameArrayBuilder();
         private readonly Stack<int> _openElementIndices = new Stack<int>();

+ 1 - 1
src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs

@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.Rendering
     /// </summary>
     internal class SimplifiedStringHashComparer : IEqualityComparer<string>
     {
-        public readonly static SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer();
+        public static readonly SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer();
 
         public bool Equals(string? x, string? y)
         {

+ 1 - 1
src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs

@@ -204,7 +204,7 @@ namespace Microsoft.AspNetCore.Components
             {
             }
 
-            private Dispatcher _dispatcher = Dispatcher.CreateDefault();
+            private readonly Dispatcher _dispatcher = Dispatcher.CreateDefault();
 
             public override Dispatcher Dispatcher => _dispatcher;
 

+ 2 - 2
src/Components/Components/test/RendererTest.cs

@@ -4443,7 +4443,7 @@ namespace Microsoft.AspNetCore.Components.Test
         private class TestComponent : IComponent, IDisposable
         {
             private RenderHandle _renderHandle;
-            private RenderFragment _renderFragment;
+            private readonly RenderFragment _renderFragment;
 
             public TestComponent(RenderFragment renderFragment)
             {
@@ -5211,7 +5211,7 @@ namespace Microsoft.AspNetCore.Components.Test
 
         private class TestErrorBoundary : AutoRenderComponent, IErrorBoundary
         {
-            private TaskCompletionSource receivedErrorTaskCompletionSource = new();
+            private readonly TaskCompletionSource receivedErrorTaskCompletionSource = new();
 
             public Exception ReceivedException { get; private set; }
             public Task ReceivedErrorTask => receivedErrorTaskCompletionSource.Task;

+ 2 - 2
src/Components/Components/test/Routing/RouteTableFactoryTests.cs

@@ -1013,8 +1013,8 @@ namespace Microsoft.AspNetCore.Components.Routing
 
         private class TestRouteTableBuilder
         {
-            IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>();
-            Type _handler = typeof(object);
+            readonly IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>();
+            readonly Type _handler = typeof(object);
 
             public TestRouteTableBuilder AddRoute(string template, Type handler = null)
             {

+ 1 - 1
src/Components/Forms/src/ValidationStateChangedEventArgs.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components.Forms
         /// <summary>
         /// Gets a shared empty instance of <see cref="ValidationStateChangedEventArgs"/>.
         /// </summary>
-        public new static readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs();
+        public static new readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs();
 
         /// <summary>
         /// Creates a new instance of <see cref="ValidationStateChangedEventArgs" />

+ 1 - 1
src/Components/Ignitor/src/NodeSerializer.cs

@@ -37,7 +37,7 @@ namespace Ignitor
             private readonly TextWriter _writer;
             private int _depth;
             private bool _atStartOfLine;
-            private HashSet<Node> _visited = new HashSet<Node>();
+            private readonly HashSet<Node> _visited = new HashSet<Node>();
 
             public Serializer(TextWriter writer)
             {

+ 1 - 1
src/Components/Server/test/Circuits/RemoteRendererTest.cs

@@ -452,7 +452,7 @@ namespace Microsoft.AspNetCore.Components.Web.Rendering
         private class TestComponent : IComponent, IHandleAfterRender
         {
             private RenderHandle _renderHandle;
-            private RenderFragment _renderFragment = (builder) =>
+            private readonly RenderFragment _renderFragment = (builder) =>
             {
                 builder.OpenElement(0, "my element");
                 builder.AddContent(1, "some text");

+ 1 - 1
src/Components/Server/test/Circuits/RenderBatchWriterTest.cs

@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.Server
 {
     public class RenderBatchWriterTest
     {
-        static object NullStringMarker = new object();
+        static readonly object NullStringMarker = new object();
 
         [Fact]
         public void CanSerializeEmptyRenderBatch()

+ 1 - 1
src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs

@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.Forms
     /// </summary>
     public static class EditContextFieldClassExtensions
     {
-        private readonly static object FieldCssClassProviderKey = new object();
+        private static readonly object FieldCssClassProviderKey = new object();
 
         /// <summary>
         /// Gets a string that indicates the status of the specified field as a CSS class. This will include

+ 1 - 1
src/Components/Web/src/Forms/FieldCssClassProvider.cs

@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Components.Forms
     /// </summary>
     public class FieldCssClassProvider
     {
-        internal readonly static FieldCssClassProvider Instance = new FieldCssClassProvider();
+        internal static readonly FieldCssClassProvider Instance = new FieldCssClassProvider();
 
         /// <summary>
         /// Gets a string that indicates the status of the specified field as a CSS class.

+ 2 - 2
src/Components/WebAssembly/Server/src/TargetPickerUi.cs

@@ -27,8 +27,8 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Server
             DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
         };
 
-        private string _browserHost;
-        private string _debugProxyUrl;
+        private readonly string _browserHost;
+        private readonly string _debugProxyUrl;
 
         /// <summary>
         /// Initialize a new instance of <see cref="TargetPickerUi"/>.

+ 1 - 1
src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs

@@ -752,7 +752,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
             public Func<RemoteAuthenticationContext<RemoteAuthenticationState>, Task<RemoteAuthenticationResult<RemoteAuthenticationState>>> CompleteSignOutCallback { get; set; }
             public Func<ValueTask<ClaimsPrincipal>> GetAuthenticatedUserCallback { get; set; }
 
-            public async override Task<AuthenticationState> GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback());
+            public override async Task<AuthenticationState> GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback());
 
             public override Task<RemoteAuthenticationResult<RemoteAuthenticationState>> CompleteSignInAsync(RemoteAuthenticationContext<RemoteAuthenticationState> context) => CompleteSignInCallback(context);
 

+ 1 - 1
src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs

@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.HotReload
     public static class WebAssemblyHotReload
     {
         private static HotReloadAgent? _hotReloadAgent;
-        private static UpdateDelta[] _updateDeltas = new[]
+        private static readonly UpdateDelta[] _updateDeltas = new[]
         {
             new UpdateDelta(),
         };

+ 1 - 1
src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs

@@ -9,7 +9,7 @@ namespace HostedInAspNet.Server
 {
     public class BootResourceRequestLog
     {
-        private ConcurrentBag<string> _requestPaths = new ConcurrentBag<string>();
+        private readonly ConcurrentBag<string> _requestPaths = new ConcurrentBag<string>();
 
         public IReadOnlyCollection<string> RequestPaths => _requestPaths;
 

+ 1 - 1
src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs

@@ -21,7 +21,7 @@ namespace Wasm.Authentication.Client
             _httpClient = new HttpClient { BaseAddress = new Uri(navigationManager.BaseUri) };
         }
 
-        public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
+        public override async ValueTask<ClaimsPrincipal> CreateUserAsync(
             OidcAccount account,
             RemoteAuthenticationUserOptions options)
         {

+ 2 - 2
src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs

@@ -19,11 +19,11 @@ namespace Microsoft.AspNetCore.Components.WebView.Photino
         // because webview2 won't let you do top-level navigation to such a URL.
         // On Linux/Mac, we must use a custom scheme, because their webviews
         // don't have a way to intercept http:// scheme requests.
-        internal readonly static string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
+        internal static readonly string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
             ? "http"
             : "app";
 
-        internal readonly static string AppBaseUri
+        internal static readonly string AppBaseUri
             = $"{BlazorAppScheme}://0.0.0.0/";
 
         public PhotinoWebViewManager(PhotinoWindow window, IServiceProvider provider, Dispatcher dispatcher, Uri appBaseUri, IFileProvider fileProvider, string hostPageRelativePath)

+ 1 - 1
src/Components/WebView/WebView/src/StaticContentProvider.cs

@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Components.WebView
         private readonly Uri _appBaseUri;
         private readonly string _hostPageRelativePath;
         private static readonly FileExtensionContentTypeProvider ContentTypeProvider = new();
-        private static ManifestEmbeddedFileProvider _manifestProvider =
+        private static readonly ManifestEmbeddedFileProvider _manifestProvider =
             new ManifestEmbeddedFileProvider(typeof(StaticContentProvider).Assembly);
 
         public StaticContentProvider(IFileProvider fileProvider, Uri appBaseUri, string hostPageRelativePath)

+ 2 - 2
src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs

@@ -9,8 +9,8 @@ namespace Microsoft.AspNetCore.Components.WebView
 {
     public class TestWebViewManager : WebViewManager
     {
-        private static Uri AppBaseUri = new Uri("app://testhost/");
-        private List<string> _sentIpcMessages = new();
+        private static readonly Uri AppBaseUri = new Uri("app://testhost/");
+        private readonly List<string> _sentIpcMessages = new();
 
         public TestWebViewManager(IServiceProvider provider, IFileProvider fileProvider)
             : base(provider, Dispatcher.CreateDefault(), AppBaseUri, fileProvider, hostPageRelativePath: "index.html")

+ 2 - 2
src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs

@@ -14,9 +14,9 @@ namespace Wasm.Performance.Driver
     class Selenium
     {
         const int SeleniumPort = 4444;
-        static bool RunHeadlessBrowser = true;
+        const bool RunHeadlessBrowser = true;
 
-        static bool PoolForBrowserLogs = true;
+        const bool PoolForBrowserLogs = true;
 
         private static async ValueTask<Uri> WaitForServerAsync(int port, CancellationToken cancellationToken)
         {

+ 1 - 1
src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs

@@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.Components
             return Task.CompletedTask;
         }
 
-        protected async virtual Task DisposeAsync()
+        protected virtual async Task DisposeAsync()
         {
             if (TestSink != null)
             {

+ 1 - 1
src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs

@@ -27,7 +27,7 @@ namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests
         {
         }
 
-        protected async override Task InitializeAsync()
+        protected override async Task InitializeAsync()
         {
             var rootUri = ServerFixture.RootUri;
             await ConnectAutomaticallyAndWait(new Uri(rootUri, "/subdir"));

+ 1 - 1
src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs

@@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Components.E2ETest.Infrastructure
 
         public PlaywrightTestBase(ITestOutputHelper output) : base(output) { }
 
-        protected async override Task InitializeCoreAsync(TestContext context)
+        protected override async Task InitializeCoreAsync(TestContext context)
         {
             BrowserManager = await BrowserManager.CreateAsync(CreateConfiguration(), LoggerFactory);
             BrowserContextInfo = new ContextInformation(LoggerFactory);

+ 2 - 2
src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs

@@ -13,8 +13,8 @@ namespace BasicTestApp
     internal class PrependMessageLoggerProvider : ILoggerProvider
     {
         ILogger _logger;
-        string _message;
-        ILogger _defaultLogger;
+        readonly string _message;
+        readonly ILogger _defaultLogger;
         private bool _disposed = false;
 
         public PrependMessageLoggerProvider(string message, IJSRuntime runtime)

+ 1 - 1
src/Components/test/testassets/TestServer/Controllers/UserController.cs

@@ -13,7 +13,7 @@ namespace Components.TestServer.Controllers
         // to the client. It's up to the developer to choose what kind of authentication state
         // data is needed on the client so it can display suitable options in the UI.
         // In this class, we inform the client only about certain roles and certain other claims.
-        static string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" };
+        static readonly string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" };
 
         // GET api/user
         [HttpGet]

+ 1 - 1
src/Components/test/testassets/TestServer/ResourceRequestLog.cs

@@ -8,7 +8,7 @@ namespace TestServer
 {
     public class ResourceRequestLog
     {
-        private List<string> _requestPaths = new List<string>();
+        private readonly List<string> _requestPaths = new List<string>();
 
         public IReadOnlyCollection<string> RequestPaths => _requestPaths;
 

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Cryptography.Cng
     /// <summary>
     /// Wraps utility BCRYPT APIs that don't work directly with handles.
     /// </summary>
-    internal unsafe static class BCryptUtil
+    internal static unsafe class BCryptUtil
     {
         /// <summary>
         /// Fills a buffer with cryptographically secure random data.

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs

@@ -13,7 +13,7 @@ using Microsoft.AspNetCore.Cryptography.Internal;
 
 namespace Microsoft.AspNetCore.Cryptography
 {
-    internal unsafe static class CryptoUtil
+    internal static unsafe class CryptoUtil
     {
         // This isn't a typical Debug.Assert; the check is always performed, even in retail builds.
         [MethodImpl(MethodImplOptions.AggressiveInlining)]

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
     /// <summary>
     /// Represents a handle to a BCrypt algorithm provider from which keys and hashes can be created.
     /// </summary>
-    internal unsafe sealed class BCryptAlgorithmHandle : BCryptHandle
+    internal sealed unsafe class BCryptAlgorithmHandle : BCryptHandle
     {
         // Called by P/Invoke when returning SafeHandles
         private BCryptAlgorithmHandle() { }

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs

@@ -6,7 +6,7 @@ using Microsoft.Win32.SafeHandles;
 
 namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 {
-    internal unsafe abstract class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
+    internal abstract unsafe class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         protected BCryptHandle()
             : base(ownsHandle: true)

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs

@@ -6,7 +6,7 @@ using Microsoft.Win32.SafeHandles;
 
 namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 {
-    internal unsafe sealed class BCryptHashHandle : BCryptHandle
+    internal sealed unsafe class BCryptHashHandle : BCryptHandle
     {
         private BCryptAlgorithmHandle? _algProviderHandle;
 

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs

@@ -6,7 +6,7 @@ using Microsoft.Win32.SafeHandles;
 
 namespace Microsoft.AspNetCore.Cryptography.SafeHandles
 {
-    internal unsafe sealed class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid
+    internal sealed unsafe class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         private NCryptDescriptorHandle()
             : base(ownsHandle: true)

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
     /// <summary>
     /// Represents a handle to a Windows module (DLL).
     /// </summary>
-    internal unsafe sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
+    internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         // Called by P/Invoke when returning SafeHandles
         private SafeLibraryHandle()

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs

@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
     /// Represents a handle returned by LocalAlloc.
     /// The memory will be zeroed out before it's freed.
     /// </summary>
-    internal unsafe sealed class SecureLocalAllocHandle : LocalAllocHandle
+    internal sealed unsafe class SecureLocalAllocHandle : LocalAllocHandle
     {
         private readonly IntPtr _cb;
 

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs

@@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Cryptography.SafeHandles;
 
 namespace Microsoft.AspNetCore.Cryptography
 {
-    internal unsafe static class UnsafeBufferUtil
+    internal static unsafe class UnsafeBufferUtil
     {
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
 #if NETSTANDARD2_0

+ 1 - 1
src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs

@@ -16,7 +16,7 @@ using Microsoft.Win32.SafeHandles;
 namespace Microsoft.AspNetCore.Cryptography
 {
     [SuppressUnmanagedCodeSecurity]
-    internal unsafe static class UnsafeNativeMethods
+    internal static unsafe class UnsafeNativeMethods
     {
         private const string BCRYPT_LIB = "bcrypt.dll";
         private static readonly Lazy<SafeLibraryHandle> _lazyBCryptLibHandle = GetLazyLibraryHandle(BCRYPT_LIB);

+ 1 - 1
src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs

@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2
     /// <summary>
     /// A PBKDF2 provider which utilizes the Win7 API BCryptDeriveKeyPBKDF2.
     /// </summary>
-    internal unsafe sealed class Win7Pbkdf2Provider : IPbkdf2Provider
+    internal sealed unsafe class Win7Pbkdf2Provider : IPbkdf2Provider
     {
         public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
         {

+ 1 - 1
src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2
     /// <summary>
     /// A PBKDF2 provider which utilizes the Win8 API BCryptKeyDerivation.
     /// </summary>
-    internal unsafe sealed class Win8Pbkdf2Provider : IPbkdf2Provider
+    internal sealed unsafe class Win8Pbkdf2Provider : IPbkdf2Provider
     {
         public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
         {

+ 1 - 1
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs

@@ -6,7 +6,7 @@ using System.Xml.Linq;
 
 namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel
 {
-    internal unsafe static class SecretExtensions
+    internal static unsafe class SecretExtensions
     {
         /// <summary>
         /// Converts an <see cref="ISecret"/> to an &lt;masterKey&gt; element which is marked

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

@@ -6,7 +6,7 @@ using System.Runtime.CompilerServices;
 
 namespace Microsoft.AspNetCore.DataProtection
 {
-    internal unsafe static class BitHelpers
+    internal static unsafe class BitHelpers
     {
         /// <summary>
         /// Writes an unsigned 32-bit value to a memory address, big-endian.

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs

@@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Cryptography.Cng;
 
 namespace Microsoft.AspNetCore.DataProtection.Cng
 {
-    internal unsafe sealed class BCryptGenRandomImpl : IBCryptGenRandom
+    internal sealed unsafe class BCryptGenRandomImpl : IBCryptGenRandom
     {
         public static readonly BCryptGenRandomImpl Instance = new BCryptGenRandomImpl();
 

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs

@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
     // An encryptor which does Encrypt(CBC) + HMAC using the Windows CNG (BCrypt*) APIs.
     // The payloads produced by this encryptor should be compatible with the payloads
     // produced by the managed Encrypt(CBC) + HMAC encryptor.
-    internal unsafe sealed class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
+    internal sealed unsafe class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
     {
         // Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single
         // key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs

@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
     // going to the IV. This means that we'll only hit the 2^-32 probability limit after 2^96 encryption
     // operations, which will realistically never happen. (At the absurd rate of one encryption operation
     // per nanosecond, it would still take 180 times the age of the universe to hit 2^96 operations.)
-    internal unsafe sealed class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
+    internal sealed unsafe class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
     {
         // Having a key modifier ensures with overwhelming probability that no two encryption operations
         // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs

@@ -12,7 +12,7 @@ using Microsoft.AspNetCore.Cryptography.SafeHandles;
 
 namespace Microsoft.AspNetCore.DataProtection.Cng
 {
-    internal unsafe static class DpapiSecretSerializerHelper
+    internal static unsafe class DpapiSecretSerializerHelper
     {
         // from ncrypt.h
         private const uint NCRYPT_SILENT_FLAG = 0x00000040;

+ 1 - 1
src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs

@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng.Internal
     /// <summary>
     /// Base class used for all CNG-related authentication encryption operations.
     /// </summary>
-    internal unsafe abstract class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable
+    internal abstract unsafe class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable
     {
         public byte[] Decrypt(ArraySegment<byte> ciphertext, ArraySegment<byte> additionalAuthenticatedData)
         {

+ 1 - 1
src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs

@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
 {
     internal static class ContainerUtils
     {
-        private static Lazy<bool> _isContainer = new Lazy<bool>(IsProcessRunningInContainer);
+        private static readonly Lazy<bool> _isContainer = new Lazy<bool>(IsProcessRunningInContainer);
         private const string RunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINER";
         private const string DeprecatedRunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINERS";
 

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

@@ -7,7 +7,7 @@ using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 {
-    internal unsafe sealed class KeyRingBasedDataProtectionProvider : IDataProtectionProvider
+    internal sealed unsafe class KeyRingBasedDataProtectionProvider : IDataProtectionProvider
     {
         private readonly IKeyRingProvider _keyRingProvider;
         private readonly ILogger _logger;

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

@@ -14,7 +14,7 @@ using Microsoft.Extensions.Logging;
 
 namespace Microsoft.AspNetCore.DataProtection.KeyManagement
 {
-    internal unsafe sealed class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector
+    internal sealed unsafe class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector
     {
         // This magic header identifies a v0 protected data blob. It's the high 28 bits of the SHA1 hash of
         // "Microsoft.AspNet.DataProtection.KeyManagement.KeyRingBasedDataProtector" [US-ASCII], big-endian.

+ 66 - 66
src/DataProtection/DataProtection/src/LoggingExtensions.cs

@@ -17,137 +17,137 @@ namespace Microsoft.Extensions.Logging
     /// </summary>
     internal static class LoggingExtensions
     {
-        private static Action<ILogger, Guid, DateTimeOffset, Exception?> _usingFallbackKeyWithExpirationAsDefaultKey;
+        private static readonly Action<ILogger, Guid, DateTimeOffset, Exception?> _usingFallbackKeyWithExpirationAsDefaultKey;
 
-        private static Action<ILogger, Guid, Exception?> _usingKeyAsDefaultKey;
+        private static readonly Action<ILogger, Guid, Exception?> _usingKeyAsDefaultKey;
 
-        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithHMAC;
+        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithHMAC;
 
-        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeCBC;
+        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeCBC;
 
-        private static Action<ILogger, Guid, string, Exception?> _performingUnprotectOperationToKeyWithPurposes;
+        private static readonly Action<ILogger, Guid, string, Exception?> _performingUnprotectOperationToKeyWithPurposes;
 
-        private static Action<ILogger, Guid, Exception?> _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
+        private static readonly Action<ILogger, Guid, Exception?> _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
 
-        private static Action<ILogger, Guid, Exception?> _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
+        private static readonly Action<ILogger, Guid, Exception?> _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
 
-        private static Action<ILogger, Guid, Exception?> _keyWasRevokedUnprotectOperationCannotProceed;
+        private static readonly Action<ILogger, Guid, Exception?> _keyWasRevokedUnprotectOperationCannotProceed;
 
-        private static Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeGCM;
+        private static readonly Action<ILogger, string, string?, Exception?> _openingCNGAlgorithmFromProviderWithChainingModeGCM;
 
-        private static Action<ILogger, string, Exception?> _usingManagedKeyedHashAlgorithm;
+        private static readonly Action<ILogger, string, Exception?> _usingManagedKeyedHashAlgorithm;
 
-        private static Action<ILogger, string, Exception?> _usingManagedSymmetricAlgorithm;
+        private static readonly Action<ILogger, string, Exception?> _usingManagedSymmetricAlgorithm;
 
-        private static Action<ILogger, Guid, string, Exception> _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
+        private static readonly Action<ILogger, Guid, string, Exception> _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
 
-        private static Action<ILogger, Guid, DateTimeOffset, Exception?> _consideringKeyWithExpirationDateAsDefaultKey;
+        private static readonly Action<ILogger, Guid, DateTimeOffset, Exception?> _consideringKeyWithExpirationDateAsDefaultKey;
 
-        private static Action<ILogger, Guid, Exception?> _keyIsNoLongerUnderConsiderationAsDefault;
+        private static readonly Action<ILogger, Guid, Exception?> _keyIsNoLongerUnderConsiderationAsDefault;
 
-        private static Action<ILogger, XName, Exception?> _unknownElementWithNameFoundInKeyringSkipping;
+        private static readonly Action<ILogger, XName, Exception?> _unknownElementWithNameFoundInKeyringSkipping;
 
-        private static Action<ILogger, Guid, Exception?> _markedKeyAsRevokedInTheKeyring;
+        private static readonly Action<ILogger, Guid, Exception?> _markedKeyAsRevokedInTheKeyring;
 
-        private static Action<ILogger, Guid, Exception?> _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
+        private static readonly Action<ILogger, Guid, Exception?> _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
 
-        private static Action<ILogger, Guid, Exception?> _foundKey;
+        private static readonly Action<ILogger, Guid, Exception?> _foundKey;
 
-        private static Action<ILogger, DateTimeOffset, Exception?> _foundRevocationOfAllKeysCreatedPriorTo;
+        private static readonly Action<ILogger, DateTimeOffset, Exception?> _foundRevocationOfAllKeysCreatedPriorTo;
 
-        private static Action<ILogger, Guid, Exception?> _foundRevocationOfKey;
+        private static readonly Action<ILogger, Guid, Exception?> _foundRevocationOfKey;
 
-        private static Action<ILogger, XElement, Exception> _exceptionWhileProcessingRevocationElement;
+        private static readonly Action<ILogger, XElement, Exception> _exceptionWhileProcessingRevocationElement;
 
-        private static Action<ILogger, DateTimeOffset, string?, Exception?> _revokingAllKeysAsOfForReason;
+        private static readonly Action<ILogger, DateTimeOffset, string?, Exception?> _revokingAllKeysAsOfForReason;
 
-        private static Action<ILogger, string, Exception?> _keyCacheExpirationTokenTriggeredByOperation;
+        private static readonly Action<ILogger, string, Exception?> _keyCacheExpirationTokenTriggeredByOperation;
 
-        private static Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElement;
+        private static readonly Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElement;
 
-        private static Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElementDebug;
+        private static readonly Action<ILogger, XElement, Exception> _anExceptionOccurredWhileProcessingTheKeyElementDebug;
 
-        private static Action<ILogger, string, Exception?> _encryptingToWindowsDPAPIForCurrentUserAccount;
+        private static readonly Action<ILogger, string, Exception?> _encryptingToWindowsDPAPIForCurrentUserAccount;
 
-        private static Action<ILogger, string, Exception?> _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
+        private static readonly Action<ILogger, string, Exception?> _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
 
-        private static Action<ILogger, string, Exception> _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
+        private static readonly Action<ILogger, string, Exception> _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
 
-        private static Action<ILogger, string, Exception?> _encryptingToX509CertificateWithThumbprint;
+        private static readonly Action<ILogger, string, Exception?> _encryptingToX509CertificateWithThumbprint;
 
-        private static Action<ILogger, string, Exception> _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
+        private static readonly Action<ILogger, string, Exception> _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
 
-        private static Action<ILogger, Guid, string, Exception?> _performingProtectOperationToKeyWithPurposes;
+        private static readonly Action<ILogger, Guid, string, Exception?> _performingProtectOperationToKeyWithPurposes;
 
-        private static Action<ILogger, Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset, Exception?> _creatingKey;
+        private static readonly Action<ILogger, Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset, Exception?> _creatingKey;
 
-        private static Action<ILogger, Guid, string, Exception?> _descriptorDeserializerTypeForKeyIs;
+        private static readonly Action<ILogger, Guid, string, Exception?> _descriptorDeserializerTypeForKeyIs;
 
-        private static Action<ILogger, Guid, Exception?> _keyEscrowSinkFoundWritingKeyToEscrow;
+        private static readonly Action<ILogger, Guid, Exception?> _keyEscrowSinkFoundWritingKeyToEscrow;
 
-        private static Action<ILogger, Guid, Exception?> _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
+        private static readonly Action<ILogger, Guid, Exception?> _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
 
-        private static Action<ILogger, Guid, Exception?> _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
+        private static readonly Action<ILogger, Guid, Exception?> _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
 
-        private static Action<ILogger, Guid, DateTimeOffset, string?, Exception?> _revokingKeyForReason;
+        private static readonly Action<ILogger, Guid, DateTimeOffset, string?, Exception?> _revokingKeyForReason;
 
-        private static Action<ILogger, string, Exception?> _readingDataFromFile;
+        private static readonly Action<ILogger, string, Exception?> _readingDataFromFile;
 
-        private static Action<ILogger, string, string, Exception?> _nameIsNotSafeFileName;
+        private static readonly Action<ILogger, string, string, Exception?> _nameIsNotSafeFileName;
 
-        private static Action<ILogger, string, Exception?> _writingDataToFile;
+        private static readonly Action<ILogger, string, Exception?> _writingDataToFile;
 
-        private static Action<ILogger, RegistryKey, string, Exception?>? _readingDataFromRegistryKeyValue;
+        private static readonly Action<ILogger, RegistryKey, string, Exception?>? _readingDataFromRegistryKeyValue;
 
-        private static Action<ILogger, string, string, Exception?> _nameIsNotSafeRegistryValueName;
+        private static readonly Action<ILogger, string, string, Exception?> _nameIsNotSafeRegistryValueName;
 
-        private static Action<ILogger, string?, Exception?> _decryptingSecretElementUsingWindowsDPAPING;
+        private static readonly Action<ILogger, string?, Exception?> _decryptingSecretElementUsingWindowsDPAPING;
 
-        private static Action<ILogger, Exception> _exceptionOccurredTryingToDecryptElement;
+        private static readonly Action<ILogger, Exception> _exceptionOccurredTryingToDecryptElement;
 
-        private static Action<ILogger, Exception?> _encryptingUsingNullEncryptor;
+        private static readonly Action<ILogger, Exception?> _encryptingUsingNullEncryptor;
 
-        private static Action<ILogger, Exception?> _usingEphemeralDataProtectionProvider;
+        private static readonly Action<ILogger, Exception?> _usingEphemeralDataProtectionProvider;
 
-        private static Action<ILogger, Exception?> _existingCachedKeyRingIsExpiredRefreshing;
+        private static readonly Action<ILogger, Exception?> _existingCachedKeyRingIsExpiredRefreshing;
 
-        private static Action<ILogger, Exception> _errorOccurredWhileRefreshingKeyRing;
+        private static readonly Action<ILogger, Exception> _errorOccurredWhileRefreshingKeyRing;
 
-        private static Action<ILogger, Exception> _errorOccurredWhileReadingKeyRing;
+        private static readonly Action<ILogger, Exception> _errorOccurredWhileReadingKeyRing;
 
-        private static Action<ILogger, Exception?> _keyRingDoesNotContainValidDefaultKey;
+        private static readonly Action<ILogger, Exception?> _keyRingDoesNotContainValidDefaultKey;
 
-        private static Action<ILogger, Exception?> _usingInmemoryRepository;
+        private static readonly Action<ILogger, Exception?> _usingInmemoryRepository;
 
-        private static Action<ILogger, Exception?> _decryptingSecretElementUsingWindowsDPAPI;
+        private static readonly Action<ILogger, Exception?> _decryptingSecretElementUsingWindowsDPAPI;
 
-        private static Action<ILogger, Exception?> _defaultKeyExpirationImminentAndRepository;
+        private static readonly Action<ILogger, Exception?> _defaultKeyExpirationImminentAndRepository;
 
-        private static Action<ILogger, Exception?> _repositoryContainsNoViableDefaultKey;
+        private static readonly Action<ILogger, Exception?> _repositoryContainsNoViableDefaultKey;
 
-        private static Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPI;
+        private static readonly Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPI;
 
-        private static Action<ILogger, Exception?> _encryptingToWindowsDPAPIForLocalMachineAccount;
+        private static readonly Action<ILogger, Exception?> _encryptingToWindowsDPAPIForLocalMachineAccount;
 
-        private static Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPING;
+        private static readonly Action<ILogger, Exception> _errorOccurredWhileEncryptingToWindowsDPAPING;
 
-        private static Action<ILogger, Exception?> _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
+        private static readonly Action<ILogger, Exception?> _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
 
-        private static Action<ILogger, Guid, Exception?> _keyRingWasLoadedOnStartup;
+        private static readonly Action<ILogger, Guid, Exception?> _keyRingWasLoadedOnStartup;
 
-        private static Action<ILogger, Exception> _keyRingFailedToLoadOnStartup;
+        private static readonly Action<ILogger, Exception> _keyRingFailedToLoadOnStartup;
 
-        private static Action<ILogger, Exception?> _usingEphemeralKeyRepository;
+        private static readonly Action<ILogger, Exception?> _usingEphemeralKeyRepository;
 
-        private static Action<ILogger, string, Exception?> _usingRegistryAsKeyRepositoryWithDPAPI;
+        private static readonly Action<ILogger, string, Exception?> _usingRegistryAsKeyRepositoryWithDPAPI;
 
-        private static Action<ILogger, string, Exception?> _usingProfileAsKeyRepository;
+        private static readonly Action<ILogger, string, Exception?> _usingProfileAsKeyRepository;
 
-        private static Action<ILogger, string, Exception?> _usingProfileAsKeyRepositoryWithDPAPI;
+        private static readonly Action<ILogger, string, Exception?> _usingProfileAsKeyRepositoryWithDPAPI;
 
-        private static Action<ILogger, string, Exception?> _usingAzureAsKeyRepository;
+        private static readonly Action<ILogger, string, Exception?> _usingAzureAsKeyRepository;
 
-        private static Action<ILogger, string, Exception?> _usingEphemeralFileSystemLocationInContainer;
+        private static readonly Action<ILogger, string, Exception?> _usingEphemeralFileSystemLocationInContainer;
 
         static LoggingExtensions()
         {

+ 1 - 1
src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs

@@ -13,7 +13,7 @@ using Microsoft.AspNetCore.DataProtection.SP800_108;
 namespace Microsoft.AspNetCore.DataProtection.Managed
 {
     // An encryptor that uses AesGcm to do encryption
-    internal unsafe sealed class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable
+    internal sealed unsafe class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable
     {
         // Having a key modifier ensures with overwhelming probability that no two encryption operations
         // will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's

+ 1 - 1
src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs

@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed
     // An encryptor which does Encrypt(CBC) + HMAC using SymmetricAlgorithm and HashAlgorithm.
     // The payloads produced by this encryptor should be compatible with the payloads
     // produced by the CNG-based Encrypt(CBC) + HMAC authenticated encryptor.
-    internal unsafe sealed class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable
+    internal sealed unsafe class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable
     {
         // Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single
         // key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block

+ 1 - 1
src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs

@@ -6,7 +6,7 @@ using System.Security.Cryptography;
 
 namespace Microsoft.AspNetCore.DataProtection.Managed
 {
-    internal unsafe sealed class ManagedGenRandomImpl : IManagedGenRandom
+    internal sealed unsafe class ManagedGenRandomImpl : IManagedGenRandom
     {
 #if NETSTANDARD2_0 || NET461
         private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();

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

@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.DataProtection
     /// <summary>
     /// Wrappers around CryptProtectMemory / CryptUnprotectMemory.
     /// </summary>
-    internal unsafe static class MemoryProtection
+    internal static unsafe class MemoryProtection
     {
         // from dpapi.h
         private const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00;

+ 1 - 1
src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs

@@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Cryptography;
 
 namespace Microsoft.AspNetCore.DataProtection.SP800_108
 {
-    internal unsafe static class SP800_108_CTR_HMACSHA512Extensions
+    internal static unsafe class SP800_108_CTR_HMACSHA512Extensions
     {
         public static void DeriveKeyWithContextHeader(this ISP800_108_CTR_HMACSHA512Provider provider, byte* pbLabel, uint cbLabel, byte[] contextHeader, byte* pbContext, uint cbContext, byte* pbDerivedKey, uint cbDerivedKey)
         {

+ 1 - 1
src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs

@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
     /// <remarks>
     /// More info at http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf, Sec. 5.1.
     /// </remarks>
-    internal unsafe static class SP800_108_CTR_HMACSHA512Util
+    internal static unsafe class SP800_108_CTR_HMACSHA512Util
     {
         // Creates a provider with an empty key.
         public static ISP800_108_CTR_HMACSHA512Provider CreateEmptyProvider()

+ 1 - 1
src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs

@@ -8,7 +8,7 @@ using Microsoft.AspNetCore.Cryptography.SafeHandles;
 
 namespace Microsoft.AspNetCore.DataProtection.SP800_108
 {
-    internal unsafe sealed class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
+    internal sealed unsafe class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
     {
         private readonly BCryptHashHandle _hashHandle;
 

+ 1 - 1
src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs

@@ -8,7 +8,7 @@ using Microsoft.AspNetCore.Cryptography.SafeHandles;
 
 namespace Microsoft.AspNetCore.DataProtection.SP800_108
 {
-    internal unsafe sealed class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
+    internal sealed unsafe class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
     {
         private readonly BCryptKeyHandle _keyHandle;
 

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

@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.DataProtection
     /// <summary>
     /// Represents a secret value stored in memory.
     /// </summary>
-    public unsafe sealed class Secret : IDisposable, ISecret
+    public sealed unsafe class Secret : IDisposable, ISecret
     {
         // from wincrypt.h
         private const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;

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

@@ -13,7 +13,7 @@ using Microsoft.AspNetCore.DataProtection.Internal;
 
 namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
 {
-    internal unsafe static class XmlEncryptionExtensions
+    internal static unsafe class XmlEncryptionExtensions
     {
         public static XElement DecryptElement(this XElement element, IActivator activator)
         {

+ 2 - 2
src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs

@@ -94,14 +94,14 @@ namespace Microsoft.AspNetCore.DataProtection.Cng.Internal
 
             public abstract byte[] DecryptHook(IntPtr pbCiphertext, uint cbCiphertext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData);
 
-            protected override sealed unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData)
+            protected sealed override unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData)
             {
                 return DecryptHook((IntPtr)pbCiphertext, cbCiphertext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData);
             }
 
             public abstract byte[] EncryptHook(IntPtr pbPlaintext, uint cbPlaintext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer);
 
-            protected override sealed unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer)
+            protected sealed override unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer)
             {
                 return EncryptHook((IntPtr)pbPlaintext, cbPlaintext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData, cbPreBuffer, cbPostBuffer);
             }

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

@@ -17,7 +17,7 @@ namespace Microsoft.AspNetCore.Hosting
         private readonly RequestDelegate _application;
         private readonly IHttpContextFactory? _httpContextFactory;
         private readonly DefaultHttpContextFactory? _defaultHttpContextFactory;
-        private HostingApplicationDiagnostics _diagnostics;
+        private readonly HostingApplicationDiagnostics _diagnostics;
 
         public HostingApplication(
             RequestDelegate application,

+ 1 - 1
src/Hosting/Hosting/src/Startup/DelegateStartup.cs

@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Hosting
     /// </summary>
     public class DelegateStartup : StartupBase<IServiceCollection>
     {
-        private Action<IApplicationBuilder> _configureApp;
+        private readonly Action<IApplicationBuilder> _configureApp;
 
         /// <summary>
         /// Creates a new <see cref="DelegateStartup" /> instance.

+ 1 - 1
src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs

@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting
 {
     internal class LoggingHandler : DelegatingHandler
     {
-        private ILogger _logger;
+        private readonly ILogger _logger;
 
         public LoggingHandler(ILoggerFactory loggerFactory, HttpMessageHandler innerHandler) : base(innerHandler)
         {

+ 1 - 1
src/Hosting/TestHost/src/ResponseBodyReaderStream.cs

@@ -68,7 +68,7 @@ namespace Microsoft.AspNetCore.TestHost
             return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
         }
 
-        public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+        public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
         {
             VerifyBuffer(buffer, offset, count);
             CheckAborted();

+ 1 - 1
src/Hosting/TestHost/src/TestServer.cs

@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.TestHost
     /// </summary>
     public class TestServer : IServer
     {
-        private IWebHost? _hostInstance;
+        private readonly IWebHost? _hostInstance;
         private bool _disposed;
         private ApplicationWrapper? _application;
 

+ 3 - 3
src/Hosting/TestHost/src/TestWebSocket.cs

@@ -48,7 +48,7 @@ namespace Microsoft.AspNetCore.TestHost
             get { return _subProtocol; }
         }
 
-        public async override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
+        public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
         {
             ThrowIfDisposed();
 
@@ -71,7 +71,7 @@ namespace Microsoft.AspNetCore.TestHost
             }
         }
 
-        public async override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
+        public override async Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
         {
             ThrowIfDisposed();
             ThrowIfOutputClosed();
@@ -264,7 +264,7 @@ namespace Microsoft.AspNetCore.TestHost
                 _messageQueue = new Queue<Message>();
             }
 
-            public async virtual Task<Message> ReceiveAsync(CancellationToken cancellationToken)
+            public virtual async Task<Message> ReceiveAsync(CancellationToken cancellationToken)
             {
                 if (_disposed)
                 {

+ 1 - 1
src/Http/Headers/src/GenericHeaderParser.cs

@@ -10,7 +10,7 @@ namespace Microsoft.Net.Http.Headers
     {
         internal delegate int GetParsedValueLengthDelegate(StringSegment value, int startIndex, out T? parsedValue);
 
-        private GetParsedValueLengthDelegate _getParsedValueLength;
+        private readonly GetParsedValueLengthDelegate _getParsedValueLength;
 
         internal GenericHeaderParser(bool supportsMultipleValues, GetParsedValueLengthDelegate getParsedValueLength)
             : base(supportsMultipleValues)

+ 1 - 1
src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs

@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Http
         // A-Z, a-z, 0-9, ., 
         // -, %, [, ], : 
         // Above for IPV6
-        private static bool[] SafeHostStringChars = {
+        private static readonly bool[] SafeHostStringChars = {
             false, false, false, false, false, false, false, false,     // 0x00 - 0x07
             false, false, false, false, false, false, false, false,     // 0x08 - 0x0F
             false, false, false, false, false, false, false, false,     // 0x10 - 0x17

+ 1 - 1
src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs

@@ -152,7 +152,7 @@ namespace Microsoft.AspNetCore.Http
         public struct Enumerator : IEnumerator<object?>
         {
             // Intentionally not readonly to prevent defensive struct copies
-            private object[] _items;
+            private readonly object[] _items;
             private int _index;
 
             internal Enumerator(EndpointMetadataCollection collection)

+ 1 - 1
src/Http/Http.Abstractions/test/UseMiddlewareTest.cs

@@ -268,7 +268,7 @@ namespace Microsoft.AspNetCore.Http
 
         private class DummyServiceProvider : IServiceProvider
         {
-            private Dictionary<Type, object> _services = new Dictionary<Type, object>();
+            private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
 
             public void AddService(Type type, object value) => _services[type] = value;
 

+ 2 - 2
src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs

@@ -168,7 +168,7 @@ namespace Microsoft.AspNetCore.Http
             }
         }
 
-        private static IDictionary<Type, object> KnownParsers = new Dictionary<Type, object>()
+        private static readonly IDictionary<Type, object> KnownParsers = new Dictionary<Type, object>()
         {
             { typeof(CacheControlHeaderValue), new Func<string, CacheControlHeaderValue?>(value => { return CacheControlHeaderValue.TryParse(value, out var result) ? result : null; }) },
             { typeof(ContentDispositionHeaderValue), new Func<string, ContentDispositionHeaderValue?>(value => { return ContentDispositionHeaderValue.TryParse(value, out var result) ? result : null; }) },
@@ -181,7 +181,7 @@ namespace Microsoft.AspNetCore.Http
             { typeof(long?), new Func<string, long?>(value => { return HeaderUtilities.TryParseNonNegativeInt64(value, out var result) ? result : null; }) },
         };
 
-        private static IDictionary<Type, object> KnownListParsers = new Dictionary<Type, object>()
+        private static readonly IDictionary<Type, object> KnownListParsers = new Dictionary<Type, object>()
         {
             { typeof(MediaTypeHeaderValue), new Func<IList<string>, IList<MediaTypeHeaderValue>>(value => { return MediaTypeHeaderValue.TryParseList(value, out var result) ? result : Array.Empty<MediaTypeHeaderValue>(); })  },
             { typeof(StringWithQualityHeaderValue), new Func<IList<string>, IList<StringWithQualityHeaderValue>>(value => { return StringWithQualityHeaderValue.TryParseList(value, out var result) ? result : Array.Empty<StringWithQualityHeaderValue>(); })  },

+ 1 - 1
src/Http/Http.Extensions/src/QueryBuilder.cs

@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Http.Extensions
     /// </summary>
     public class QueryBuilder : IEnumerable<KeyValuePair<string, string>>
     {
-        private IList<KeyValuePair<string, string>> _params;
+        private readonly IList<KeyValuePair<string, string>> _params;
 
         /// <summary>
         /// Initializes a new instance of <see cref="QueryBuilder"/>.

+ 1 - 1
src/Http/Http/src/Features/RequestBodyPipeFeature.cs

@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Http.Features
     {
         private PipeReader? _internalPipeReader;
         private Stream? _streamInstanceWhenWrapped;
-        private HttpContext _context;
+        private readonly HttpContext _context;
 
         /// <summary>
         /// Initializes a new instance of <see cref="IRequestBodyPipeFeature"/>.

+ 1 - 1
src/Http/Http/src/Features/RequestCookiesFeature.cs

@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Http.Features
     public class RequestCookiesFeature : IRequestCookiesFeature
     {
         // Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624
-        private readonly static Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
+        private static readonly Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
 
         private FeatureReferences<IHttpRequestFeature> _features;
         private StringValues _original;

+ 2 - 2
src/Http/Http/src/FormCollection.cs

@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Http
         private static readonly IEnumerator<KeyValuePair<string, StringValues>> EmptyIEnumeratorType = default(Enumerator);
         private static readonly IEnumerator EmptyIEnumerator = default(Enumerator);
 
-        private static IFormFileCollection EmptyFiles = new FormFileCollection();
+        private static readonly IFormFileCollection EmptyFiles = new FormFileCollection();
 
         private IFormFileCollection? _files;
 
@@ -174,7 +174,7 @@ namespace Microsoft.AspNetCore.Http
         {
             // Do NOT make this readonly, or MoveNext will not work
             private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
-            private bool _notEmpty;
+            private readonly bool _notEmpty;
 
             internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator)
             {

+ 1 - 1
src/Http/Http/src/HeaderDictionary.cs

@@ -376,7 +376,7 @@ namespace Microsoft.AspNetCore.Http
         {
             // Do NOT make this readonly, or MoveNext will not work
             private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
-            private bool _notEmpty;
+            private readonly bool _notEmpty;
 
             internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator)
             {

+ 1 - 1
src/Http/Http/src/HttpContextAccessor.cs

@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Http
     /// </summary>
     public class HttpContextAccessor : IHttpContextAccessor
     {
-        private static AsyncLocal<HttpContextHolder> _httpContextCurrent = new AsyncLocal<HttpContextHolder>();
+        private static readonly AsyncLocal<HttpContextHolder> _httpContextCurrent = new AsyncLocal<HttpContextHolder>();
 
         /// <inheritdoc/>
         public HttpContext? HttpContext

+ 3 - 3
src/Http/Http/src/Internal/DefaultConnectionInfo.cs

@@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Http
     internal sealed class DefaultConnectionInfo : ConnectionInfo
     {
         // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
-        private readonly static Func<IFeatureCollection, IHttpConnectionFeature> _newHttpConnectionFeature = f => new HttpConnectionFeature();
-        private readonly static Func<IFeatureCollection, ITlsConnectionFeature> _newTlsConnectionFeature = f => new TlsConnectionFeature();
-        private readonly static Func<IFeatureCollection, IConnectionLifetimeNotificationFeature> _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get<IHttpResponseFeature>());
+        private static readonly Func<IFeatureCollection, IHttpConnectionFeature> _newHttpConnectionFeature = f => new HttpConnectionFeature();
+        private static readonly Func<IFeatureCollection, ITlsConnectionFeature> _newTlsConnectionFeature = f => new TlsConnectionFeature();
+        private static readonly Func<IFeatureCollection, IConnectionLifetimeNotificationFeature> _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get<IHttpResponseFeature>());
 
         private FeatureReferences<FeatureInterfaces> _features;
 

+ 6 - 6
src/Http/Http/src/Internal/DefaultHttpRequest.cs

@@ -18,12 +18,12 @@ namespace Microsoft.AspNetCore.Http
         private const string Https = "https";
 
         // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
-        private readonly static Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
-        private readonly static Func<IFeatureCollection, IQueryFeature?> _newQueryFeature = f => new QueryFeature(f);
-        private readonly static Func<DefaultHttpRequest, IFormFeature> _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default);
-        private readonly static Func<IFeatureCollection, IRequestCookiesFeature> _newRequestCookiesFeature = f => new RequestCookiesFeature(f);
-        private readonly static Func<IFeatureCollection, IRouteValuesFeature> _newRouteValuesFeature = f => new RouteValuesFeature();
-        private readonly static Func<HttpContext, IRequestBodyPipeFeature> _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context);
+        private static readonly Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
+        private static readonly Func<IFeatureCollection, IQueryFeature?> _newQueryFeature = f => new QueryFeature(f);
+        private static readonly Func<DefaultHttpRequest, IFormFeature> _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default);
+        private static readonly Func<IFeatureCollection, IRequestCookiesFeature> _newRequestCookiesFeature = f => new RequestCookiesFeature(f);
+        private static readonly Func<IFeatureCollection, IRouteValuesFeature> _newRouteValuesFeature = f => new RouteValuesFeature();
+        private static readonly Func<HttpContext, IRequestBodyPipeFeature> _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context);
 
         private readonly DefaultHttpContext _context;
         private FeatureReferences<FeatureInterfaces> _features;

+ 3 - 3
src/Http/Http/src/Internal/DefaultWebSocketManager.cs

@@ -13,11 +13,11 @@ namespace Microsoft.AspNetCore.Http
     internal sealed class DefaultWebSocketManager : WebSocketManager
     {
         // Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
-        private readonly static Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
-        private readonly static Func<IFeatureCollection, IHttpWebSocketFeature?> _nullWebSocketFeature = f => null;
+        private static readonly Func<IFeatureCollection, IHttpRequestFeature?> _nullRequestFeature = f => null;
+        private static readonly Func<IFeatureCollection, IHttpWebSocketFeature?> _nullWebSocketFeature = f => null;
 
         private FeatureReferences<FeatureInterfaces> _features;
-        private readonly static WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext();
+        private static readonly WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext();
 
         public DefaultWebSocketManager(IFeatureCollection features)
         {

+ 2 - 2
src/Http/Http/src/Internal/ItemsDictionary.cs

@@ -140,7 +140,7 @@ namespace Microsoft.AspNetCore.Http
         private class EmptyEnumerator : IEnumerator<KeyValuePair<object, object?>>
         {
             // In own class so only initalized if GetEnumerator is called on an empty ItemsDictionary
-            public readonly static IEnumerator<KeyValuePair<object, object?>> Instance = new EmptyEnumerator();
+            public static readonly IEnumerator<KeyValuePair<object, object?>> Instance = new EmptyEnumerator();
             public KeyValuePair<object, object?> Current => default;
 
             object? IEnumerator.Current => null;
@@ -157,7 +157,7 @@ namespace Microsoft.AspNetCore.Http
         private static class EmptyDictionary
         {
             // In own class so only initalized if CopyTo is called on an empty ItemsDictionary
-            public readonly static IDictionary<object, object?> Dictionary = new Dictionary<object, object?>();
+            public static readonly IDictionary<object, object?> Dictionary = new Dictionary<object, object?>();
             public static ICollection<KeyValuePair<object, object?>> Collection => Dictionary;
         }
     }

+ 1 - 1
src/Http/Http/src/Internal/RequestCookieCollection.cs

@@ -178,7 +178,7 @@ namespace Microsoft.AspNetCore.Http
         {
             // Do NOT make this readonly, or MoveNext will not work
             private AdaptiveCapacityDictionary<string, string>.Enumerator _dictionaryEnumerator;
-            private bool _notEmpty;
+            private readonly bool _notEmpty;
 
             internal Enumerator(AdaptiveCapacityDictionary<string, string>.Enumerator dictionaryEnumerator)
             {

+ 1 - 1
src/Http/Http/src/QueryCollection.cs

@@ -190,7 +190,7 @@ namespace Microsoft.AspNetCore.Http
         {
             // Do NOT make this readonly, or MoveNext will not work
             private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
-            private bool _notEmpty;
+            private readonly bool _notEmpty;
 
             internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator)
             {

+ 1 - 1
src/Http/Http/src/QueryCollectionInternal.cs

@@ -83,7 +83,7 @@ namespace Microsoft.AspNetCore.Http
         {
             // Do NOT make this readonly, or MoveNext will not work
             private AdaptiveCapacityDictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
-            private bool _notEmpty;
+            private readonly bool _notEmpty;
 
             internal Enumerator(AdaptiveCapacityDictionary<string, StringValues>.Enumerator dictionaryEnumerator)
             {

+ 1 - 1
src/Http/Http/test/DefaultHttpContextTests.cs

@@ -405,7 +405,7 @@ namespace Microsoft.AspNetCore.Http
 
         private class TestSession : ISession
         {
-            private Dictionary<string, byte[]> _store
+            private readonly Dictionary<string, byte[]> _store
                 = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
 
             public string Id { get; set; }

+ 1 - 1
src/Http/Http/test/Features/NonSeekableReadStream.cs

@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Http.Features
 {
     public class NonSeekableReadStream : Stream
     {
-        private Stream _inner;
+        private readonly Stream _inner;
 
         public NonSeekableReadStream(byte[] data)
             : this(new MemoryStream(data))

+ 1 - 1
src/Http/Http/test/Internal/DefaultHttpResponseTests.cs

@@ -198,7 +198,7 @@ namespace Microsoft.AspNetCore.Http
 
         public class ResponseFeature : IHttpResponseFeature
         {
-            private List<(Func<object, Task>, object)> _callbacks = new();
+            private readonly List<(Func<object, Task>, object)> _callbacks = new();
             public int StatusCode { get; set; }
             public string ReasonPhrase { get; set; }
             public IHeaderDictionary Headers { get; set; }

+ 1 - 1
src/Http/Owin/test/OwinExtensionTests.cs

@@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Owin
 
     public class OwinExtensionTests
     {
-        static AppFunc notFound = env => new Task(() => { env["owin.ResponseStatusCode"] = 404; });
+        static readonly AppFunc notFound = env => new Task(() => { env["owin.ResponseStatusCode"] = 404; });
 
         [Fact]
         public async Task OwinConfigureServiceProviderAddsServices()

+ 1 - 1
src/Http/Routing/perf/Microbenchmarks/Matching/MatcherBuilderMultipleEntryBenchmark.cs

@@ -187,7 +187,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
 
         private abstract class TestMatcherPolicyBase : MatcherPolicy
         {
-            private int _order;
+            private readonly int _order;
 
             protected TestMatcherPolicyBase(int order)
             {

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor