Browse Source

Enable more code analysis rules (#33303)

Adds CA1842, CA1843, CA2008-CA2011, CA2013, CA2014, CA2016, CA2200, CA2208
Pranav K 4 years ago
parent
commit
98a8d7a2be
88 changed files with 269 additions and 411 deletions
  1. 36 0
      .editorconfig
  2. 1 1
      src/Analyzers/Analyzers/src/CompilationFeatureDetector.cs
  3. 3 2
      src/Components/Ignitor/src/CancellableOperation.cs
  4. 1 1
      src/Components/Server/src/Circuits/CircuitHost.cs
  5. 1 1
      src/Components/Server/src/Circuits/RemoteJSRuntime.cs
  6. 11 10
      src/Components/Server/src/Circuits/RemoteRenderer.cs
  7. 2 0
      src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj
  8. 2 1
      src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs
  9. 1 1
      src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs
  10. 1 1
      src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/NetCorePbkdf2Provider.cs
  11. 5 5
      src/DataProtection/DataProtection/src/AuthenticatedEncryption/AuthenticatedEncryptorFactory.cs
  12. 2 2
      src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs
  13. 4 2
      src/Hosting/Hosting/src/WebHostExtensions.cs
  14. 1 1
      src/Hosting/TestHost/src/HttpContextBuilder.cs
  15. 2 2
      src/Hosting/TestHost/src/TestWebSocket.cs
  16. 2 2
      src/Http/Headers/src/ContentDispositionHeaderValue.cs
  17. 1 1
      src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs
  18. 1 1
      src/Http/Http/src/HeaderDictionary.cs
  19. 2 1
      src/Http/Owin/src/WebSockets/OwinWebSocketAcceptAdapter.cs
  20. 3 3
      src/Http/Routing/src/Patterns/RoutePatternFactory.cs
  21. 1 1
      src/Http/WebUtilities/src/HttpRequestStreamReader.cs
  22. 1 1
      src/Identity/EntityFrameworkCore/src/UserStore.cs
  23. 1 1
      src/JSInterop/Microsoft.JSInterop/src/Infrastructure/DotNetDispatcher.cs
  24. 2 2
      src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs
  25. 2 2
      src/Logging.AzureAppServices/src/AzureBlobLoggerOptions.cs
  26. 1 1
      src/Logging.AzureAppServices/src/AzureFileLoggerOptions.cs
  27. 2 2
      src/Middleware/ConcurrencyLimiter/src/QueuePolicies/QueuePolicy.cs
  28. 5 5
      src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs
  29. 1 1
      src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs
  30. 2 2
      src/Middleware/ResponseCaching/src/Streams/ResponseCachingStream.cs
  31. 1 1
      src/Middleware/Rewrite/src/ApacheModRewrite/CookieActionFactory.cs
  32. 2 2
      src/Middleware/Rewrite/src/ApacheModRewrite/FlagParser.cs
  33. 3 3
      src/Middleware/Rewrite/src/IISUrlRewrite/IISRewriteMap.cs
  34. 1 1
      src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs
  35. 2 2
      src/Middleware/Rewrite/src/RedirectRule.cs
  36. 2 2
      src/Middleware/Rewrite/src/RewriteRule.cs
  37. 1 1
      src/Middleware/Rewrite/src/UrlActions/ChangeCookieAction.cs
  38. 9 2
      src/Middleware/Rewrite/src/UrlMatches/IntegerMatch.cs
  39. 8 1
      src/Middleware/Rewrite/src/UrlMatches/StringMatch.cs
  40. 1 1
      src/Middleware/Rewrite/test/ApacheModRewrite/FlagParserTest.cs
  41. 1 1
      src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs
  42. 2 2
      src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs
  43. 10 12
      src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs
  44. 1 1
      src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamReader.cs
  45. 1 1
      src/Mvc/Mvc.Analyzers/src/MvcFacts.cs
  46. 1 5
      src/Mvc/Mvc.Api.Analyzers/src/ActualApiResponseMetadataFactory.cs
  47. 0 22
      src/Mvc/Mvc.Api.Analyzers/src/AddResponseTypeAttributeCodeFixAction.cs
  48. 0 5
      src/Mvc/Mvc.Api.Analyzers/src/ApiActionsDoNotRequireExplicitModelValidationCodeFixProvider.cs
  49. 2 2
      src/Mvc/Mvc.Api.Analyzers/src/SymbolApiConventionMatcher.cs
  50. 1 1
      src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs
  51. 2 4
      src/Mvc/Mvc.TagHelpers/test/ComponentTagHelperTest.cs
  52. 1 1
      src/Mvc/Mvc.TagHelpers/test/GlobbingUrlBuilderTest.cs
  53. 1 1
      src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs
  54. 0 180
      src/Mvc/Mvc.ViewFeatures/src/Infrastructure/ArrayBufferWriter.cs
  55. 3 2
      src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs
  56. 1 0
      src/Mvc/Mvc.ViewFeatures/src/Microsoft.AspNetCore.Mvc.ViewFeatures.csproj
  57. 2 2
      src/Mvc/Mvc.ViewFeatures/test/Filters/SaveTempDataFilterTest.cs
  58. 3 3
      src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/NamespaceDirective.cs
  59. 4 4
      src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/GreenNode.cs
  60. 1 1
      src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxListBuilder.cs
  61. 2 2
      src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxListOfT.cs
  62. 1 1
      src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs
  63. 2 2
      src/Servers/Kestrel/Core/src/Internal/Http/Http1OutputProducer.cs
  64. 2 6
      src/Servers/Kestrel/Core/src/Internal/Infrastructure/ConnectionManager.cs
  65. 3 3
      src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs
  66. 2 2
      src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportManager.cs
  67. 2 1
      src/Servers/Kestrel/Core/src/Internal/KestrelServerImpl.cs
  68. 1 1
      src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerContext.cs
  69. 1 1
      src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionListener.cs
  70. 1 1
      src/Shared/Components/PrerenderComponentApplicationStore.cs
  71. 1 1
      src/Shared/Dictionary/AdaptiveCapacityDictionary.cs
  72. 9 10
      src/Shared/PooledArrayBufferWriter.cs
  73. 3 3
      src/Shared/TaskToApm.cs
  74. 1 1
      src/Shared/runtime/Http2/Hpack/H2StaticTable.Http2.cs
  75. 3 1
      src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs
  76. 29 28
      src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs
  77. 2 0
      src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs
  78. 6 1
      src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LongPollingTransport.cs
  79. 1 1
      src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/SendUtils.cs
  80. 8 3
      src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs
  81. 6 8
      src/SignalR/common/Http.Connections/src/Internal/Transports/ServerSentEventsServerTransport.cs
  82. 7 7
      src/SignalR/common/Shared/MemoryBufferWriter.cs
  83. 1 1
      src/SignalR/common/Shared/PipeWriterStream.cs
  84. 1 1
      src/SignalR/common/SignalR.Common/src/Protocol/HubMethodInvocationMessage.cs
  85. 4 0
      src/SignalR/server/Core/src/HubConnectionContext.cs
  86. 1 1
      src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs
  87. 1 1
      src/Testing/src/xunit/SkipOnHelixAttribute.cs
  88. 1 1
      src/Tools/dotnet-dev-certs/src/ReporterEventListener.cs

+ 36 - 0
.editorconfig

@@ -146,15 +146,45 @@ dotnet_diagnostic.CA1840.severity = warning
 # CA1841: Prefer Dictionary.Contains methods
 dotnet_diagnostic.CA1841.severity = warning
 
+# CA1842: Do not use 'WhenAll' with a single task
+dotnet_diagnostic.CA1842.severity = warning
+
+# CA1843: Do not use 'WaitAll' with a single task
+dotnet_diagnostic.CA1843.severity = warning
+
 # CA1845: Use span-based 'string.Concat'
 dotnet_diagnostic.CA1845.severity = warning
 
 # CA1846: Prefer AsSpan over Substring
 dotnet_diagnostic.CA1846.severity = warning
 
+# CA2008: Do not create tasks without passing a TaskScheduler
+dotnet_diagnostic.CA2008.severity = warning
+
+# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value
+dotnet_diagnostic.CA2009.severity = warning
+
+# CA2011: Avoid infinite recursion
+dotnet_diagnostic.CA2011.severity = warning
+
 # CA2012: Use ValueTask correctly
 dotnet_diagnostic.CA2012.severity = warning
 
+# CA2013: Do not use ReferenceEquals with value types
+dotnet_diagnostic.CA2013.severity = warning
+
+# CA2014: Do not use stackalloc in loops.
+dotnet_diagnostic.CA2014.severity = warning
+
+# CA2016: Forward the 'CancellationToken' parameter to methods that take one
+dotnet_diagnostic.CA2016.severity = warning
+
+# CA2200: Rethrow to preserve stack details
+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
@@ -186,10 +216,16 @@ dotnet_diagnostic.CA1837.severity = suggestion
 dotnet_diagnostic.CA1838.severity = suggestion
 # CA1841: Prefer Dictionary.Contains methods
 dotnet_diagnostic.CA1841.severity = suggestion
+# CA1844: Provide memory-based overrides of async methods when subclassing 'Stream'
+dotnet_diagnostic.CA1844.severity = suggestion
 # CA1845: Use span-based 'string.Concat'
 dotnet_diagnostic.CA1845.severity = suggestion
 # CA1846: Prefer AsSpan over Substring
 dotnet_diagnostic.CA1846.severity = suggestion
+# CA2008: Do not create tasks without passing a TaskScheduler
+dotnet_diagnostic.CA2008.severity = suggestion
 # CA2012: Use ValueTask correctly
 dotnet_diagnostic.CA2012.severity = suggestion
 
+# CA2016: Forward the 'CancellationToken' parameter to methods that take one
+dotnet_diagnostic.CA2016.severity = suggestion

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

@@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.Analyzers
                     var semanticModel = compilation.GetSemanticModel(syntaxReferences[j].SyntaxTree);
 
                     var syntax = await syntaxReferences[j].GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
-                    var operation = semanticModel.GetOperation(syntax);
+                    var operation = semanticModel.GetOperation(syntax, cancellationToken);
 
                     // Look for a call to one of the SignalR gestures that applies to the Configure method.
                     if (operation

+ 3 - 2
src/Components/Ignitor/src/CancellableOperation.cs

@@ -22,8 +22,9 @@ namespace Ignitor
                     operation.Dispose();
                 },
                 this,
-                TaskContinuationOptions.ExecuteSynchronously); // We need to execute synchronously to clean-up before anything else continues
-
+                cancellationToken,
+                TaskContinuationOptions.ExecuteSynchronously, // We need to execute synchronously to clean-up before anything else continues
+                TaskScheduler.Default);
 
             Cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
 

+ 1 - 1
src/Components/Server/src/Circuits/CircuitHost.cs

@@ -50,7 +50,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
             if (CircuitId.Secret is null)
             {
                 // Prevent the use of a 'default' secret.
-                throw new ArgumentException(nameof(circuitId));
+                throw new ArgumentException($"Property '{nameof(CircuitId.Secret)}' cannot be null.", nameof(circuitId));
             }
 
             _scope = scope;

+ 1 - 1
src/Components/Server/src/Circuits/RemoteJSRuntime.cs

@@ -122,7 +122,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
 
             if (_maximumIncomingBytes - data.Length < _byteArraysToBeRevivedTotalBytes)
             {
-                throw new ArgumentOutOfRangeException("Exceeded the maximum byte array transfer limit for a call.");
+                throw new ArgumentOutOfRangeException(nameof(data), "Exceeded the maximum byte array transfer limit for a call.");
             }
 
             // We also store the total number of bytes seen so far to compare against

+ 11 - 10
src/Components/Server/src/Circuits/RemoteRenderer.cs

@@ -62,7 +62,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
             var componentId = AssignRootComponentId(component);
 
             var attachComponentTask = _client.SendAsync("JS.AttachComponent", componentId, domElementSelector);
-            CaptureAsyncExceptions(attachComponentTask);
+            _ = CaptureAsyncExceptions(attachComponentTask);
 
             return RenderRootComponentAsync(componentId);
         }
@@ -80,7 +80,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
             var componentId = AssignRootComponentId(component);
 
             var attachComponentTask = _client.SendAsync("JS.AttachComponent", componentId, domElementSelector);
-            CaptureAsyncExceptions(attachComponentTask);
+            _ = CaptureAsyncExceptions(attachComponentTask);
 
             return RenderRootComponentAsync(componentId, parameters);
         }
@@ -324,7 +324,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
             CompleteRender(entry.CompletionSource, errorMessageOrNull);
         }
 
-        private void CompleteRender(TaskCompletionSource pendingRenderInfo, string? errorMessageOrNull)
+        private static void CompleteRender(TaskCompletionSource pendingRenderInfo, string? errorMessageOrNull)
         {
             if (errorMessageOrNull == null)
             {
@@ -352,15 +352,16 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
             public ValueStopwatch ValueStopwatch { get; }
         }
 
-        private void CaptureAsyncExceptions(Task task)
+        private async Task CaptureAsyncExceptions(Task task)
         {
-            task.ContinueWith(t =>
+            try
             {
-                if (t.IsFaulted)
-                {
-                    UnhandledException?.Invoke(this, t.Exception);
-                }
-            });
+                await task;
+            }
+            catch (Exception exception)
+            {
+                UnhandledException?.Invoke(this, exception);
+            }
         }
 
         private static class Log

+ 2 - 0
src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj

@@ -27,7 +27,9 @@
     <Reference Include="System.Text.Json" PrivateAssets="All" />
     
     <Compile Include="$(SharedSourceRoot)ValueStopwatch\*.cs" />
+
     <Compile Include="$(SharedSourceRoot)LinkerFlags.cs" LinkBase="Shared" />
+    <Compile Include="$(SharedSourceRoot)\PooledArrayBufferWriter.cs" LinkBase="Shared" />
 
     <!-- Add a project dependency without reference output assemblies to enforce build order -->
     <!-- Applying workaround for https://github.com/microsoft/msbuild/issues/2661 and https://github.com/dotnet/sdk/issues/952 -->

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

@@ -4,6 +4,7 @@
 using System;
 using System.IO;
 using System.Runtime.InteropServices;
+using System.Threading;
 using System.Threading.Tasks;
 using Microsoft.Extensions.FileProviders;
 using PhotinoNET;
@@ -40,7 +41,7 @@ namespace Microsoft.AspNetCore.Components.WebView.Photino
                     var messageOriginUrl = new Uri(AppBaseUri);
 
                     MessageReceived(messageOriginUrl, (string)message!);
-                }, message);
+                }, message, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
             };
         }
 

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

@@ -49,7 +49,7 @@ namespace Wasm.Performance.Driver
                     }
                 }
 
-                await Task.Delay(1000);
+                await Task.Delay(1000, cancellationToken);
             }
 
             throw new Exception($"Unable to connect to selenium-server at {uri}");

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

@@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2
                     algorithmName = HashAlgorithmName.SHA512;
                     break;
                 default:
-                    throw new ArgumentOutOfRangeException();
+                    throw new ArgumentOutOfRangeException(nameof(prf));
             }
 
             return Rfc2898DeriveBytes.Pbkdf2(password, salt, iterationCount, algorithmName, numBytesRequested);

+ 5 - 5
src/DataProtection/DataProtection/src/AuthenticatedEncryption/AuthenticatedEncryptorFactory.cs

@@ -127,7 +127,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                     return 256;
 
                 default:
-                    throw new ArgumentOutOfRangeException(nameof(EncryptionAlgorithm));
+                    throw new ArgumentOutOfRangeException(nameof(algorithm));
             }
         }
 
@@ -144,7 +144,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                     return Constants.BCRYPT_AES_ALGORITHM;
 
                 default:
-                    throw new ArgumentOutOfRangeException(nameof(EncryptionAlgorithm));
+                    throw new ArgumentOutOfRangeException(nameof(algorithm));
             }
         }
 
@@ -159,7 +159,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                     return Constants.BCRYPT_SHA512_ALGORITHM;
 
                 default:
-                    throw new ArgumentOutOfRangeException(nameof(ValidationAlgorithm));
+                    throw new ArgumentOutOfRangeException(nameof(algorithm));
             }
         }
 
@@ -176,7 +176,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                     return typeof(Aes);
 
                 default:
-                    throw new ArgumentOutOfRangeException(nameof(EncryptionAlgorithm));
+                    throw new ArgumentOutOfRangeException(nameof(algorithm));
             }
         }
 
@@ -191,7 +191,7 @@ namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption
                     return typeof(HMACSHA512);
 
                 default:
-                    throw new ArgumentOutOfRangeException(nameof(ValidationAlgorithm));
+                    throw new ArgumentOutOfRangeException(nameof(algorithm));
             }
         }
     }

+ 2 - 2
src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs

@@ -152,7 +152,7 @@ namespace Microsoft.AspNetCore.JsonPatch.IntegrationTests
 
             // Assert
             Assert.Null(targetObject.SimpleObject.StringProperty);
-        }     
+        }
 
         [Fact]
         public void CopyStringProperty_ToAnotherStringProperty()
@@ -344,7 +344,7 @@ namespace Microsoft.AspNetCore.JsonPatch.IntegrationTests
                 {
                     if (value == null)
                     {
-                        throw new ArgumentNullException();
+                        throw new ArgumentNullException(nameof(value));
                     }
 
                     stringProperty = value;

+ 4 - 2
src/Hosting/Hosting/src/WebHostExtensions.cs

@@ -153,11 +153,11 @@ namespace Microsoft.AspNetCore.Hosting
             }
         }
 
-        private static async Task WaitForTokenShutdownAsync(this IWebHost host, CancellationToken token)
+        private static async Task WaitForTokenShutdownAsync(this IWebHost host, CancellationToken cancellationToken)
         {
             var applicationLifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();
 
-            token.Register(state =>
+            cancellationToken.Register(state =>
             {
                 ((IHostApplicationLifetime)state!).StopApplication();
             },
@@ -173,7 +173,9 @@ namespace Microsoft.AspNetCore.Hosting
             await waitForStop.Task;
 
             // WebHost will use its default ShutdownTimeout if none is specified.
+#pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods. StopAsync should not be canceled by the token to RunAsync.
             await host.StopAsync();
+#pragma warning restore CA2016
         }
     }
 }

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

@@ -150,7 +150,7 @@ namespace Microsoft.AspNetCore.TestHost
             // Async offload, don't let the test code block the caller.
             if (_preserveExecutionContext)
             {
-                _ = Task.Factory.StartNew(RunRequestAsync);
+                _ = Task.Factory.StartNew(RunRequestAsync, default, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
             }
             else
             {

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

@@ -207,11 +207,11 @@ namespace Microsoft.AspNetCore.TestHost
             }
             if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length)
             {
-                throw new ArgumentOutOfRangeException(nameof(buffer.Offset), buffer.Offset, string.Empty);
+                throw new ArgumentOutOfRangeException(nameof(buffer), buffer.Offset, string.Empty);
             }
             if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset)
             {
-                throw new ArgumentOutOfRangeException(nameof(buffer.Count), buffer.Count, string.Empty);
+                throw new ArgumentOutOfRangeException(nameof(buffer), buffer.Count, string.Empty);
             }
         }
 

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

@@ -764,7 +764,7 @@ namespace Microsoft.Net.Http.Headers
                 || ((digit >= 'A') && (digit <= 'F'))
                 || ((digit >= 'a') && (digit <= 'f'))))
             {
-                throw new ArgumentException();
+                throw new ArgumentOutOfRangeException(nameof(digit));
             }
 
             var res = (digit <= '9')
@@ -778,7 +778,7 @@ namespace Microsoft.Net.Http.Headers
                 || ((next >= 'A') && (next <= 'F'))
                 || ((next >= 'a') && (next <= 'f'))))
             {
-                throw new ArgumentException();
+                throw new ArgumentOutOfRangeException(nameof(next));
             }
 
             return (byte)((res << 4) + ((next <= '9')

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

@@ -675,7 +675,7 @@ namespace Microsoft.AspNetCore.Routing
             {
                 if (dictionary == null)
                 {
-                    throw new ArgumentNullException();
+                    throw new ArgumentNullException(nameof(dictionary));
                 }
 
                 _dictionary = dictionary;

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

@@ -187,7 +187,7 @@ namespace Microsoft.AspNetCore.Http
         {
             if (item.Key == null)
             {
-                throw new ArgumentNullException("The key is null");
+                throw new ArgumentException("The key is null");
             }
             ThrowIfReadOnly();
             EnsureStore(1);

+ 2 - 1
src/Http/Owin/src/WebSockets/OwinWebSocketAcceptAdapter.cs

@@ -4,6 +4,7 @@
 using System;
 using System.Collections.Generic;
 using System.Net.WebSockets;
+using System.Threading;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http;
 
@@ -129,7 +130,7 @@ namespace Microsoft.AspNetCore.Owin
                     {
                         adapter.UpstreamTask = next(environment);
                         adapter.UpstreamWentAsyncTcs.TrySetResult(0);
-                        adapter.UpstreamTask.ContinueWith(adapter.EnsureCompleted, TaskContinuationOptions.ExecuteSynchronously);
+                        adapter.UpstreamTask.ContinueWith(adapter.EnsureCompleted, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
                     }
                     catch (Exception ex)
                     {

+ 3 - 3
src/Http/Routing/src/Patterns/RoutePatternFactory.cs

@@ -682,7 +682,7 @@ namespace Microsoft.AspNetCore.Routing.Patterns
 
             if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
             {
-                throw new ArgumentNullException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue, nameof(parameterKind));
+                throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
             }
 
             return ParameterPartCore(
@@ -719,7 +719,7 @@ namespace Microsoft.AspNetCore.Routing.Patterns
 
             if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
             {
-                throw new ArgumentNullException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue, nameof(parameterKind));
+                throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
             }
 
             if (parameterPolicies == null)
@@ -761,7 +761,7 @@ namespace Microsoft.AspNetCore.Routing.Patterns
 
             if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
             {
-                throw new ArgumentNullException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue, nameof(parameterKind));
+                throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
             }
 
             if (parameterPolicies == null)

+ 1 - 1
src/Http/WebUtilities/src/HttpRequestStreamReader.cs

@@ -294,7 +294,7 @@ namespace Microsoft.AspNetCore.WebUtilities
                     do
                     {
                         Debug.Assert(charsRemaining == 0);
-                        _bytesRead = await _stream.ReadAsync(_byteBuffer.AsMemory(0, _byteBufferSize));
+                        _bytesRead = await _stream.ReadAsync(_byteBuffer.AsMemory(0, _byteBufferSize), cancellationToken);
                         if (_bytesRead == 0)  // EOF
                         {
                             _isBlocked = true;

+ 1 - 1
src/Identity/EntityFrameworkCore/src/UserStore.cs

@@ -636,7 +636,7 @@ namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore
             cancellationToken.ThrowIfCancellationRequested();
             ThrowIfDisposed();
 
-            return Users.SingleOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail);
+            return Users.SingleOrDefaultAsync(u => u.NormalizedEmail == normalizedEmail, cancellationToken);
         }
 
         /// <summary>

+ 1 - 1
src/JSInterop/Microsoft.JSInterop/src/Infrastructure/DotNetDispatcher.cs

@@ -325,7 +325,7 @@ namespace Microsoft.JSInterop.Infrastructure
         {
             if (string.IsNullOrWhiteSpace(assemblyKey.AssemblyName))
             {
-                throw new ArgumentException("Cannot be null, empty, or whitespace.", nameof(assemblyKey.AssemblyName));
+                throw new ArgumentException($"Property '{nameof(AssemblyKey.AssemblyName)}' cannot be null, empty, or whitespace.", nameof(assemblyKey));
             }
 
             if (string.IsNullOrWhiteSpace(methodIdentifier))

+ 2 - 2
src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs

@@ -22,8 +22,8 @@ namespace Microsoft.JSInterop.Infrastructure
                 DotNetDispatcher.Invoke(new TestJSRuntime(), new DotNetInvocationInfo(" ", "SomeMethod", default, default), "[]");
             });
 
-            Assert.StartsWith("Cannot be null, empty, or whitespace.", ex.Message);
-            Assert.Equal("AssemblyName", ex.ParamName);
+            Assert.StartsWith("Property 'AssemblyName' cannot be null, empty, or whitespace.", ex.Message);
+            Assert.Equal("assemblyKey", ex.ParamName);
         }
 
         [Fact]

+ 2 - 2
src/Logging.AzureAppServices/src/AzureBlobLoggerOptions.cs

@@ -24,7 +24,7 @@ namespace Microsoft.Extensions.Logging.AzureAppServices
             {
                 if (string.IsNullOrEmpty(value))
                 {
-                    throw new ArgumentException(nameof(value), $"{nameof(BlobName)} must be non-empty string.");
+                    throw new ArgumentException($"{nameof(BlobName)} must be non-empty string.", nameof(value));
                 }
                 _blobName = value;
             }
@@ -39,7 +39,7 @@ namespace Microsoft.Extensions.Logging.AzureAppServices
             var timestamp = context.Timestamp;
             return $"{context.AppName}/{timestamp.Year}/{timestamp.Month:00}/{timestamp.Day:00}/{timestamp.Hour:00}/{context.Identifier}";
         };
-       
+
         internal string ContainerUrl { get; set; }
 
         internal string ApplicationName { get; set; }

+ 1 - 1
src/Logging.AzureAppServices/src/AzureFileLoggerOptions.cs

@@ -62,7 +62,7 @@ namespace Microsoft.Extensions.Logging.AzureAppServices
             {
                 if (string.IsNullOrEmpty(value))
                 {
-                    throw new ArgumentException(nameof(value));
+                    throw new ArgumentNullException(nameof(value));
                 }
                 _fileName = value;
             }

+ 2 - 2
src/Middleware/ConcurrencyLimiter/src/QueuePolicies/QueuePolicy.cs

@@ -24,13 +24,13 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter
             var maxConcurrentRequests = queuePolicyOptions.MaxConcurrentRequests;
             if (maxConcurrentRequests <= 0)
             {
-                throw new ArgumentException("MaxConcurrentRequests must be a positive integer.", nameof(maxConcurrentRequests));
+                throw new ArgumentException("MaxConcurrentRequests must be a positive integer.", nameof(options));
             }
 
             var requestQueueLimit = queuePolicyOptions.RequestQueueLimit;
             if (requestQueueLimit < 0)
             {
-                throw new ArgumentException("The RequestQueueLimit cannot be a negative number.", nameof(requestQueueLimit));
+                throw new ArgumentException("The RequestQueueLimit cannot be a negative number.", nameof(options));
             }
 
             _serverSemaphore = new SemaphoreSlim(maxConcurrentRequests);

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

@@ -99,13 +99,13 @@ namespace Microsoft.AspNetCore.HttpOverrides
             _next = next;
 
             PreProcessHosts();
-        }
 
-        private static void EnsureOptionNotNullorWhitespace(string value, string propertyName)
-        {
-            if (string.IsNullOrWhiteSpace(value))
+            static void EnsureOptionNotNullorWhitespace(string value, string propertyName)
             {
-                throw new ArgumentException($"options.{propertyName} is required", "options");
+                if (string.IsNullOrWhiteSpace(value))
+                {
+                    throw new ArgumentException($"options.{propertyName} is required", nameof(options));
+                }
             }
         }
 

+ 1 - 1
src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs

@@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
 
                 Copy(segment, destination);
 
-                await destination.FlushAsync();
+                await destination.FlushAsync(cancellationToken);
             }
         }
 

+ 2 - 2
src/Middleware/ResponseCaching/src/Streams/ResponseCachingStream.cs

@@ -91,7 +91,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
             try
             {
                 _startResponseCallback();
-                await _innerStream.FlushAsync();
+                await _innerStream.FlushAsync(cancellationToken);
             }
             catch
             {
@@ -131,7 +131,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
         }
 
         public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
-            await WriteAsync(buffer.AsMemory(offset, count));
+            await WriteAsync(buffer.AsMemory(offset, count), cancellationToken);
 
         public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
         {

+ 1 - 1
src/Middleware/Rewrite/src/ApacheModRewrite/CookieActionFactory.cs

@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Rewrite.ApacheModRewrite
         {
             if (string.IsNullOrEmpty(flagValue))
             {
-                throw new ArgumentException(nameof(flagValue));
+                throw new ArgumentNullException(nameof(flagValue));
             }
 
             var i = 0;

+ 2 - 2
src/Middleware/Rewrite/src/ApacheModRewrite/FlagParser.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;
@@ -59,7 +59,7 @@ namespace Microsoft.AspNetCore.Rewrite.ApacheModRewrite
         {
             if (string.IsNullOrEmpty(flagString))
             {
-                throw new ArgumentException(nameof(flagString));
+                throw new ArgumentException("Argument cannot be null or empty string.", nameof(flagString));
             }
 
             // Check that flags are contained within []

+ 3 - 3
src/Middleware/Rewrite/src/IISUrlRewrite/IISRewriteMap.cs

@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Rewrite.IISUrlRewrite
         {
             if (string.IsNullOrEmpty(name))
             {
-                throw new ArgumentException(nameof(name));
+                throw new ArgumentNullException(nameof(name));
             }
             Name = name;
         }
@@ -31,11 +31,11 @@ namespace Microsoft.AspNetCore.Rewrite.IISUrlRewrite
             {
                 if (string.IsNullOrEmpty(key))
                 {
-                    throw new ArgumentException(nameof(key));
+                    throw new ArgumentNullException(nameof(key));
                 }
                 if (string.IsNullOrEmpty(value))
                 {
-                    throw new ArgumentException(nameof(value));
+                    throw new ArgumentNullException(nameof(value));
                 }
                 _map[key] = value;
             }

+ 1 - 1
src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs

@@ -59,7 +59,7 @@ namespace Microsoft.AspNetCore.Rewrite
 
             if (reader == null)
             {
-                throw new ArgumentException(nameof(reader));
+                throw new ArgumentNullException(nameof(reader));
             }
 
             var rules = new UrlRewriteFileParser().Parse(reader, alwaysUseManagedServerVariables);

+ 2 - 2
src/Middleware/Rewrite/src/RedirectRule.cs

@@ -20,12 +20,12 @@ namespace Microsoft.AspNetCore.Rewrite
         {
             if (string.IsNullOrEmpty(regex))
             {
-                throw new ArgumentException(nameof(regex));
+                throw new ArgumentNullException(nameof(regex));
             }
 
             if (string.IsNullOrEmpty(replacement))
             {
-                throw new ArgumentException(nameof(replacement));
+                throw new ArgumentNullException(nameof(replacement));
             }
 
             InitialMatch = new Regex(regex, RegexOptions.Compiled | RegexOptions.CultureInvariant, _regexTimeout);

+ 2 - 2
src/Middleware/Rewrite/src/RewriteRule.cs

@@ -19,12 +19,12 @@ namespace Microsoft.AspNetCore.Rewrite
         {
             if (string.IsNullOrEmpty(regex))
             {
-                throw new ArgumentException(nameof(regex));
+                throw new ArgumentNullException(nameof(regex));
             }
 
             if (string.IsNullOrEmpty(replacement))
             {
-                throw new ArgumentException(nameof(replacement));
+                throw new ArgumentNullException(nameof(replacement));
             }
 
             InitialMatch = new Regex(regex, RegexOptions.Compiled | RegexOptions.CultureInvariant, _regexTimeout);

+ 1 - 1
src/Middleware/Rewrite/src/UrlActions/ChangeCookieAction.cs

@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Rewrite.UrlActions
 
             if (string.IsNullOrEmpty(name))
             {
-                throw new ArgumentException(nameof(name));
+                throw new ArgumentNullException(nameof(name));
             }
 
             Name = name;

+ 9 - 2
src/Middleware/Rewrite/src/UrlMatches/IntegerMatch.cs

@@ -2,8 +2,8 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Diagnostics;
 using System.Globalization;
-using Microsoft.AspNetCore.Rewrite;
 
 namespace Microsoft.AspNetCore.Rewrite.UrlMatches
 {
@@ -25,6 +25,12 @@ namespace Microsoft.AspNetCore.Rewrite.UrlMatches
                 throw new FormatException(Resources.Error_IntegerMatch_FormatExceptionMessage);
             }
             _value = compValue;
+
+            if (operation < IntegerOperationType.Equal || operation > IntegerOperationType.NotEqual)
+            {
+                throw new ArgumentOutOfRangeException(nameof(operation));
+            }
+
             _operation = operation;
         }
 
@@ -51,7 +57,8 @@ namespace Microsoft.AspNetCore.Rewrite.UrlMatches
                 case IntegerOperationType.NotEqual:
                     return compValue != _value ? MatchResults.EmptySuccess : MatchResults.EmptyFailure;
                 default:
-                    throw new ArgumentOutOfRangeException("operation"); // Will never be thrown
+                    Debug.Fail("This is never reached.");
+                    throw new InvalidOperationException(); // Will never be thrown
             }
         }
     }

+ 8 - 1
src/Middleware/Rewrite/src/UrlMatches/StringMatch.cs

@@ -2,6 +2,7 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System;
+using System.Diagnostics;
 
 namespace Microsoft.AspNetCore.Rewrite.UrlMatches
 {
@@ -14,6 +15,11 @@ namespace Microsoft.AspNetCore.Rewrite.UrlMatches
         public StringMatch(string value, StringOperationType operation, bool ignoreCase)
         {
             _value = value;
+            if (operation < StringOperationType.Equal || operation > StringOperationType.LessEqual)
+            {
+                throw new ArgumentOutOfRangeException(nameof(operation));
+            }
+
             _operation = operation;
             _stringComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
         }
@@ -33,7 +39,8 @@ namespace Microsoft.AspNetCore.Rewrite.UrlMatches
                 case StringOperationType.LessEqual:
                     return string.Compare(input, _value, _stringComparison) <= 0 ? MatchResults.EmptySuccess : MatchResults.EmptyFailure;
                 default:
-                    throw new ArgumentOutOfRangeException("operation"); // Will never be thrown
+                    Debug.Fail("This is never reached.");
+                    throw new InvalidOperationException(); // Will never be thrown
             }
         }
     }

+ 1 - 1
src/Middleware/Rewrite/test/ApacheModRewrite/FlagParserTest.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/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs

@@ -33,7 +33,7 @@ namespace Microsoft.AspNetCore.SpaServices.AngularCli
             var devServerPort = spaBuilder.Options.DevServerPort;
             if (string.IsNullOrEmpty(sourcePath))
             {
-                throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
+                throw new ArgumentException("Property 'SourcePath' cannot be null or empty", nameof(spaBuilder));
             }
 
             if (string.IsNullOrEmpty(scriptName))

+ 2 - 2
src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs

@@ -169,7 +169,7 @@ namespace Microsoft.AspNetCore.SpaServices.Extensions.Proxy
             // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
             context.Response.Headers.Remove("transfer-encoding");
 
-            using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
+            using (var responseStream = await responseMessage.Content.ReadAsStreamAsync(cancellationToken))
             {
                 await responseStream.CopyToAsync(context.Response.Body, StreamCopyBufferSize, cancellationToken);
             }
@@ -292,7 +292,7 @@ namespace Microsoft.AspNetCore.SpaServices.Extensions.Proxy
                         break;
                     }
 
-                    await Task.Delay(100);
+                    await Task.Delay(100, cancellationToken);
                 }
 
                 var result = resultTask.Result; // We know it's completed already

+ 10 - 12
src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs

@@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer
             var devServerPort = spaBuilder.Options.DevServerPort;
             if (string.IsNullOrEmpty(sourcePath))
             {
-                throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
+                throw new ArgumentException("Property 'SourcePath' cannot be null or empty", nameof(spaBuilder));
             }
 
             if (string.IsNullOrEmpty(scriptName))
@@ -49,23 +49,21 @@ namespace Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer
             var diagnosticSource = appBuilder.ApplicationServices.GetRequiredService<DiagnosticSource>();
             var portTask = StartCreateReactAppServerAsync(sourcePath, scriptName, pkgManagerCommand, devServerPort, logger, diagnosticSource, applicationStoppingToken);
 
-            // Everything we proxy is hardcoded to target http://localhost because:
-            // - the requests are always from the local machine (we're not accepting remote
-            //   requests that go directly to the create-react-app server)
-            // - given that, there's no reason to use https, and we couldn't even if we
-            //   wanted to, because in general the create-react-app server has no certificate
-            var targetUriTask = portTask.ContinueWith(
-                task => new UriBuilder("http", "localhost", task.Result).Uri);
-
-            SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, () =>
+            SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, async () =>
             {
                 // On each request, we create a separate startup task with its own timeout. That way, even if
                 // the first request times out, subsequent requests could still work.
                 var timeout = spaBuilder.Options.StartupTimeout;
-                return targetUriTask.WithTimeout(timeout,
-                    $"The create-react-app server did not start listening for requests " +
+                var port = await portTask.WithTimeout(timeout, $"The create-react-app server did not start listening for requests " +
                     $"within the timeout period of {timeout.Seconds} seconds. " +
                     $"Check the log output for error information.");
+
+                // Everything we proxy is hardcoded to target http://localhost because:
+                // - the requests are always from the local machine (we're not accepting remote
+                //   requests that go directly to the create-react-app server)
+                // - given that, there's no reason to use https, and we couldn't even if we
+                //   wanted to, because in general the create-react-app server has no certificate
+                return new UriBuilder("http", "localhost", port).Uri;
             });
         }
 

+ 1 - 1
src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamReader.cs

@@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.NodeServices.Util
         {
             _streamReader = streamReader ?? throw new ArgumentNullException(nameof(streamReader));
             _linesBuffer = new StringBuilder();
-            Task.Factory.StartNew(Run);
+            Task.Factory.StartNew(Run, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
         }
 
         public Task<Match> WaitForMatch(Regex regex)

+ 1 - 1
src/Mvc/Mvc.Analyzers/src/MvcFacts.cs

@@ -105,7 +105,7 @@ namespace Microsoft.AspNetCore.Mvc.Analyzers
             {
                 if (method.OverriddenMethod == null)
                 {
-                    throw new ArgumentNullException(nameof(method.OverriddenMethod));
+                    throw new InvalidOperationException($"{nameof(method.OverriddenMethod)} cannot be null.");
                 }
 
                 method = method.OverriddenMethod;

+ 1 - 5
src/Mvc/Mvc.Api.Analyzers/src/ActualApiResponseMetadataFactory.cs

@@ -101,10 +101,6 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
 
                 case ObjectCreationExpressionSyntax creation:
                     {
-                        if (creation.ArgumentList == null)
-                        {
-                            throw new ArgumentNullException(nameof(creation.ArgumentList));
-                        }
                         // Read values from 'return new StatusCodeResult(200) case.
                         var result = InspectMethodArguments(semanticModel, creation, creation.ArgumentList, cancellationToken);
                         statusCode = result.statusCode ?? statusCode;
@@ -205,7 +201,7 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
         private static ITypeSymbol? GetExpressionObjectType(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
         {
             var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken);
-            
+
             return typeInfo.Type;
         }
 

+ 0 - 22
src/Mvc/Mvc.Api.Analyzers/src/AddResponseTypeAttributeCodeFixAction.cs

@@ -121,40 +121,18 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
                 }
             }
 
-            if (root == null)
-            {
-                throw new ArgumentNullException(nameof(root));
-            }
-
             return document.WithSyntaxRoot(root);
         }
 
         private async Task<CodeActionContext?> CreateCodeActionContext(CancellationToken cancellationToken)
         {
             var root = await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
-
-            if (root == null)
-            {
-                throw new ArgumentNullException(nameof(root));
-            }
-
             var semanticModel = await _document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
             var methodReturnStatement = (ReturnStatementSyntax)root.FindNode(_diagnostic.Location.SourceSpan);
             var methodSyntax = methodReturnStatement.FirstAncestorOrSelf<MethodDeclarationSyntax>();
             var method = semanticModel.GetDeclaredSymbol(methodSyntax, cancellationToken);
 
-            if (semanticModel == null)
-            {
-                throw new ArgumentNullException(nameof(semanticModel));
-            }
-
             var statusCodesType = semanticModel.Compilation.GetTypeByMetadataName(ApiSymbolNames.HttpStatusCodes);
-
-            if (statusCodesType == null)
-            {
-                throw new ArgumentNullException(nameof(statusCodesType));
-            }
-
             var statusCodeConstants = GetStatusCodeConstants(statusCodesType);
 
             if (!ApiControllerSymbolCache.TryCreate(semanticModel.Compilation, out var symbolCache))

+ 0 - 5
src/Mvc/Mvc.Api.Analyzers/src/ApiActionsDoNotRequireExplicitModelValidationCodeFixProvider.cs

@@ -60,11 +60,6 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
                 var rootNode = await _document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                 var editor = await DocumentEditor.CreateAsync(_document, cancellationToken).ConfigureAwait(false);
 
-                if (rootNode == null)
-                {
-                    throw new ArgumentNullException(nameof(rootNode));
-                }
-
                 var ifBlockSyntax = rootNode!.FindNode(_ifBlockSpan);
                 editor.RemoveNode(ifBlockSyntax);
 

+ 2 - 2
src/Mvc/Mvc.Api.Analyzers/src/SymbolApiConventionMatcher.cs

@@ -72,7 +72,7 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
 
             if (argEnum == null)
             {
-                throw new ArgumentNullException(nameof(argEnum));
+                throw new InvalidOperationException($"{nameof(symbolCache.ApiConventionNameMatchAttribute)} does not appear well formed.");
             }
 
             var intValue = (int)argEnum;
@@ -94,7 +94,7 @@ namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
 
             if (argEnum == null)
             {
-                throw new ArgumentNullException(nameof(argEnum));
+                throw new ArgumentNullException(nameof(symbol));
             }
 
             var intValue = (int)argEnum;

+ 1 - 1
src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs

@@ -97,7 +97,7 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
 
             if (_renderMode is null)
             {
-                throw new ArgumentException(Resources.FormatAttributeIsRequired(RenderModeName, TagHelperName), nameof(RenderMode));
+                throw new InvalidOperationException(Resources.FormatAttributeIsRequired(RenderModeName, TagHelperName));
             }
 
             var requestServices = ViewContext.HttpContext.RequestServices;

+ 2 - 4
src/Mvc/Mvc.TagHelpers/test/ComponentTagHelperTest.cs

@@ -55,10 +55,8 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
             var output = GetTagHelperOutput();
 
             // Act & Assert
-            await ExceptionAssert.ThrowsArgumentAsync(
-                () => tagHelper.ProcessAsync(context, output),
-                nameof(RenderMode),
-                "A value for the 'render-mode' attribute must be supplied to the 'component' tag helper.");
+            var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output));
+            Assert.Equal("A value for the 'render-mode' attribute must be supplied to the 'component' tag helper.", ex.Message);
         }
 
         private static TagHelperContext GetTagHelperContext()

+ 1 - 1
src/Mvc/Mvc.TagHelpers/test/GlobbingUrlBuilderTest.cs

@@ -461,7 +461,7 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
         {
             if (rootNode.Children == null || !rootNode.Children.Any())
             {
-                throw new ArgumentException(nameof(rootNode));
+                throw new ArgumentNullException(nameof(rootNode));
             }
 
             var fileProvider = new Mock<IFileProvider>(MockBehavior.Strict);

+ 1 - 1
src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs

@@ -122,7 +122,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers
 
             if (buffer.Length - index < count)
             {
-                throw new ArgumentOutOfRangeException(nameof(buffer.Length));
+                throw new ArgumentOutOfRangeException(nameof(buffer));
             }
 
             Buffer.AppendHtml(new string(buffer, index, count));

+ 0 - 180
src/Mvc/Mvc.ViewFeatures/src/Infrastructure/ArrayBufferWriter.cs

@@ -1,180 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Buffers;
-using System.Diagnostics;
-
-namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure
-{
-    // Note: this is currently an internal class that will be replaced with a shared version.
-    internal sealed class ArrayBufferWriter<T> : IBufferWriter<T>, IDisposable
-    {
-        private T[] _rentedBuffer;
-        private int _index;
-
-        private const int MinimumBufferSize = 256;
-
-        public ArrayBufferWriter()
-        {
-            _rentedBuffer = ArrayPool<T>.Shared.Rent(MinimumBufferSize);
-            _index = 0;
-        }
-
-        public ArrayBufferWriter(int initialCapacity)
-        {
-            if (initialCapacity <= 0)
-                throw new ArgumentException(nameof(initialCapacity));
-
-            _rentedBuffer = ArrayPool<T>.Shared.Rent(initialCapacity);
-            _index = 0;
-        }
-
-        public ReadOnlyMemory<T> WrittenMemory
-        {
-            get
-            {
-                CheckIfDisposed();
-
-                return _rentedBuffer.AsMemory(0, _index);
-            }
-        }
-
-        public int WrittenCount
-        {
-            get
-            {
-                CheckIfDisposed();
-
-                return _index;
-            }
-        }
-
-        public int Capacity
-        {
-            get
-            {
-                CheckIfDisposed();
-
-                return _rentedBuffer.Length;
-            }
-        }
-
-        public int FreeCapacity
-        {
-            get
-            {
-                CheckIfDisposed();
-
-                return _rentedBuffer.Length - _index;
-            }
-        }
-
-        public void Clear()
-        {
-            CheckIfDisposed();
-
-            ClearHelper();
-        }
-
-        private void ClearHelper()
-        {
-            Debug.Assert(_rentedBuffer != null);
-
-            _rentedBuffer.AsSpan(0, _index).Clear();
-            _index = 0;
-        }
-
-        // Returns the rented buffer back to the pool
-        public void Dispose()
-        {
-            if (_rentedBuffer == null)
-            {
-                return;
-            }
-
-            ClearHelper();
-            ArrayPool<T>.Shared.Return(_rentedBuffer);
-            _rentedBuffer = null;
-        }
-
-        private void CheckIfDisposed()
-        {
-            if (_rentedBuffer == null)
-            {
-                throw new ObjectDisposedException(nameof(ArrayBufferWriter<T>));
-            }
-        }
-
-        public void Advance(int count)
-        {
-            CheckIfDisposed();
-
-            if (count < 0)
-                throw new ArgumentException(nameof(count));
-
-            if (_index > _rentedBuffer.Length - count)
-                ThrowInvalidOperationException(_rentedBuffer.Length);
-
-            _index += count;
-        }
-
-        public Memory<T> GetMemory(int sizeHint = 0)
-        {
-            CheckIfDisposed();
-
-            CheckAndResizeBuffer(sizeHint);
-            return _rentedBuffer.AsMemory(_index);
-        }
-
-        public Span<T> GetSpan(int sizeHint = 0)
-        {
-            CheckIfDisposed();
-
-            CheckAndResizeBuffer(sizeHint);
-            return _rentedBuffer.AsSpan(_index);
-        }
-
-        private void CheckAndResizeBuffer(int sizeHint)
-        {
-            Debug.Assert(_rentedBuffer != null);
-
-            if (sizeHint < 0)
-                throw new ArgumentException(nameof(sizeHint));
-
-            if (sizeHint == 0)
-            {
-                sizeHint = MinimumBufferSize;
-            }
-
-            int availableSpace = _rentedBuffer.Length - _index;
-
-            if (sizeHint > availableSpace)
-            {
-                int growBy = Math.Max(sizeHint, _rentedBuffer.Length);
-
-                int newSize = checked(_rentedBuffer.Length + growBy);
-
-                T[] oldBuffer = _rentedBuffer;
-
-                _rentedBuffer = ArrayPool<T>.Shared.Rent(newSize);
-
-                Debug.Assert(oldBuffer.Length >= _index);
-                Debug.Assert(_rentedBuffer.Length >= _index);
-
-                Span<T> previousBuffer = oldBuffer.AsSpan(0, _index);
-                previousBuffer.CopyTo(_rentedBuffer);
-                previousBuffer.Clear();
-                ArrayPool<T>.Shared.Return(oldBuffer);
-            }
-
-            Debug.Assert(_rentedBuffer.Length - _index > 0);
-            Debug.Assert(_rentedBuffer.Length - _index >= sizeHint);
-        }
-
-        private static void ThrowInvalidOperationException(int capacity)
-        {
-            throw new InvalidOperationException($"Cannot advance past the end of the buffer, which has a size of {capacity}.");
-        }
-    }
-}

+ 3 - 2
src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs

@@ -1,7 +1,8 @@
-// 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;
+using System.Buffers;
 using System.Collections.Generic;
 using System.Text.Json;
 
@@ -136,7 +137,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure
                 return Array.Empty<byte>();
             }
 
-            using (var bufferWriter = new ArrayBufferWriter<byte>())
+            using (var bufferWriter = new PooledArrayBufferWriter<byte>())
             {
                 using var writer = new Utf8JsonWriter(bufferWriter);
                 writer.WriteStartObject();

+ 1 - 0
src/Mvc/Mvc.ViewFeatures/src/Microsoft.AspNetCore.Mvc.ViewFeatures.csproj

@@ -39,6 +39,7 @@
     <Compile Include="$(RepoRoot)src\Shared\Components\ComponentParameter.cs" />
     <Compile Include="$(SharedSourceRoot)Components\PrerenderComponentApplicationStore.cs" />
     <Compile Include="$(SharedSourceRoot)Components\ProtectedPrerenderComponentApplicationStore.cs" />
+    <Compile Include="$(SharedSourceRoot)\PooledArrayBufferWriter.cs" LinkBase="Infrastructure" />
   </ItemGroup>
 
 </Project>

+ 2 - 2
src/Mvc/Mvc.ViewFeatures/test/Filters/SaveTempDataFilterTest.cs

@@ -419,7 +419,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
             {
                 if (_hasStarted)
                 {
-                    throw new ArgumentException();
+                    throw new TimeZoneNotFoundException();
                 }
 
                 var prior = _responseStartingAsync;
@@ -437,4 +437,4 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
             }
         }
     }
-}
+}

+ 3 - 3
src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/NamespaceDirective.cs

@@ -30,7 +30,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X
         {
             if (builder == null)
             {
-                throw new ArgumentNullException();
+                throw new ArgumentNullException(nameof(builder));
             }
 
             builder.AddDirective(Directive);
@@ -128,7 +128,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X
         // both 'view engine' style paths and absolute paths.
         //
         // We also don't normalize the separators here. We expect that all documents are using a consistent style of path.
-        // 
+        //
         // If we can't normalize the path, we just return null so it will be ignored.
         private static string NormalizeDirectory(string path)
         {
@@ -193,7 +193,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X
         {
             if (builder == null)
             {
-                throw new ArgumentNullException();
+                throw new ArgumentNullException(nameof(builder));
             }
 
             builder.AddDirective(Directive);

+ 4 - 4
src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/GreenNode.cs

@@ -53,7 +53,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
                 {
                     if (annotation == null)
                     {
-                        throw new ArgumentException(nameof(annotations), "Annotation cannot be null");
+                        throw new ArgumentException("Annotation cannot be null", nameof(annotations));
                     }
                 }
 
@@ -281,7 +281,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
             var stack = new Stack<StackEntry>();
             stack.Push(new StackEntry(this, leading, trailing));
 
-            // Separated out stack processing logic so that it does not unintentionally refer to 
+            // Separated out stack processing logic so that it does not unintentionally refer to
             // "this", "leading" or "trailing.
             ProcessStack(writer, stack);
         }
@@ -297,7 +297,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
         }
         #endregion
 
-        #region Tokens 
+        #region Tokens
 
         public virtual object GetValue()
         {
@@ -384,7 +384,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
         }
         #endregion
 
-        #region Equivalence 
+        #region Equivalence
         public virtual bool IsEquivalentTo(GreenNode other)
         {
             if (this == other)

+ 1 - 1
src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxListBuilder.cs

@@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
         {
             if (item == null)
             {
-                throw new ArgumentNullException();
+                throw new ArgumentNullException(nameof(item));
             }
 
             if (_nodes == null || Count >= _nodes.Length)

+ 2 - 2
src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxListOfT.cs

@@ -88,7 +88,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
                         return (TNode)Node;
                     }
                 }
-                throw new ArgumentOutOfRangeException();
+                throw new ArgumentOutOfRangeException(nameof(index));
             }
         }
 
@@ -288,7 +288,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Syntax
             }
             else
             {
-                throw new ArgumentException(nameof(nodeInList));
+                throw new ArgumentOutOfRangeException(nameof(nodeInList));
             }
         }
 

+ 1 - 1
src/Servers/IIS/IIS/src/Core/IISHttpContext.FeatureCollection.cs

@@ -476,7 +476,7 @@ namespace Microsoft.AspNetCore.Server.IIS.Core
         {
             if (errorCode < 0)
             {
-                throw new ArgumentOutOfRangeException("'errorCode' cannot be negative");
+                throw new ArgumentOutOfRangeException(nameof(errorCode), "'errorCode' cannot be negative");
             }
 
             SetResetCode(errorCode);

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

@@ -257,7 +257,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
                     {
                         if (_currentSegment.Length - bytes < _position)
                         {
-                            throw new ArgumentOutOfRangeException("Can't advance past buffer size.");
+                            throw new ArgumentOutOfRangeException(nameof(bytes), "Can't advance past buffer size.");
                         }
 
                         _position += bytes;
@@ -267,7 +267,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
                 {
                     if (_advancedBytesForChunk > _currentChunkMemory.Length - _currentMemoryPrefixBytes - EndChunkLength - bytes)
                     {
-                        throw new ArgumentOutOfRangeException("Can't advance past buffer size.");
+                        throw new ArgumentOutOfRangeException(nameof(bytes), "Can't advance past buffer size.");
                     }
                     _advancedBytesForChunk += bytes;
                 }

+ 2 - 6
src/Servers/Kestrel/Core/src/Internal/Infrastructure/ConnectionManager.cs

@@ -3,10 +3,6 @@
 
 using System;
 using System.Collections.Concurrent;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Connections;
 
 namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
 {
@@ -35,7 +31,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
         {
             if (!_connectionReferences.TryAdd(id, connectionReference))
             {
-                throw new ArgumentException(nameof(id));
+                throw new ArgumentException("Unable to add connection.", nameof(id));
             }
         }
 
@@ -43,7 +39,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
         {
             if (!_connectionReferences.TryRemove(id, out var reference))
             {
-                throw new ArgumentException(nameof(id));
+                throw new ArgumentException("Unable to remove connection.", nameof(id));
             }
 
             if (reference.TryGetConnection(out var connection))

+ 3 - 3
src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportConnectionManager.cs

@@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
 
             if (!_connectionReferences.TryAdd(id, connectionReference))
             {
-                throw new ArgumentException(nameof(id));
+                throw new ArgumentException("Unable to add specified id.", nameof(id));
             }
 
             _connectionManager.AddConnection(id, connectionReference);
@@ -38,7 +38,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
         {
             if (!_connectionReferences.TryRemove(id, out _))
             {
-                throw new ArgumentException(nameof(id));
+                throw new ArgumentException("No value found for the specified id.", nameof(id));
             }
 
             _connectionManager.RemoveConnection(id);
@@ -50,7 +50,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
         {
             if (!_connectionReferences.TryRemove(id, out _))
             {
-                throw new ArgumentException(nameof(id));
+                throw new ArgumentException("No value found for the specified id.", nameof(id));
             }
         }
 

+ 2 - 2
src/Servers/Kestrel/Core/src/Internal/Infrastructure/TransportManager.cs

@@ -180,7 +180,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
                  => _connectionListener.AcceptAsync(cancellationToken);
 
             public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
-                => _connectionListener.UnbindAsync();
+                => _connectionListener.UnbindAsync(cancellationToken);
 
             public ValueTask DisposeAsync()
                 => _connectionListener.DisposeAsync();
@@ -201,7 +201,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
                  => _multiplexedConnectionListener.AcceptAsync(features: null, cancellationToken);
 
             public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
-                => _multiplexedConnectionListener.UnbindAsync();
+                => _multiplexedConnectionListener.UnbindAsync(cancellationToken);
 
             public ValueTask DisposeAsync()
                 => _multiplexedConnectionListener.DisposeAsync();

+ 2 - 1
src/Servers/Kestrel/Core/src/Internal/KestrelServerImpl.cs

@@ -222,8 +222,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core
 
             _stopCts.Cancel();
 
-            // Don't use cancellationToken when acquiring the semaphore. Dispose calls this with a pre-canceled token.
+#pragma warning disable CA2016 // Don't use cancellationToken when acquiring the semaphore. Dispose calls this with a pre-canceled token.
             await _bindSemaphore.WaitAsync().ConfigureAwait(false);
+#pragma warning restore CA2016
 
             try
             {

+ 1 - 1
src/Servers/Kestrel/Transport.Libuv/src/Internal/ListenerContext.cs

@@ -41,7 +41,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.Internal
 
         public async ValueTask<LibuvConnection> AcceptAsync(CancellationToken cancellationToken = default)
         {
-            while (await _acceptQueue.Reader.WaitToReadAsync())
+            while (await _acceptQueue.Reader.WaitToReadAsync(cancellationToken))
             {
                 while (_acceptQueue.Reader.TryRead(out var connection))
                 {

+ 1 - 1
src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionListener.cs

@@ -117,7 +117,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets
                 {
                     Debug.Assert(_listenSocket != null, "Bind must be called first.");
 
-                    var acceptSocket = await _listenSocket.AcceptAsync();
+                    var acceptSocket = await _listenSocket.AcceptAsync(cancellationToken);
 
                     // Only apply no delay to Tcp based endpoints
                     if (acceptSocket.LocalEndPoint is IPEndPoint)

+ 1 - 1
src/Shared/Components/PrerenderComponentApplicationStore.cs

@@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.Components
             }
 
             ExistingState = JsonSerializer.Deserialize<Dictionary<string, byte[]>>(Convert.FromBase64String(existingState)) ??
-                throw new ArgumentException(nameof(existingState));
+                throw new ArgumentNullException(nameof(existingState));
         }
 
 #nullable enable

+ 1 - 1
src/Shared/Dictionary/AdaptiveCapacityDictionary.cs

@@ -638,7 +638,7 @@ namespace Microsoft.AspNetCore.Internal
             {
                 if (dictionary == null)
                 {
-                    throw new ArgumentNullException();
+                    throw new ArgumentNullException(nameof(dictionary));
                 }
 
                 _dictionary = dictionary;

+ 9 - 10
src/Components/Server/src/BlazorPack/ArrayBufferWriter.cs → src/Shared/PooledArrayBufferWriter.cs

@@ -3,31 +3,28 @@
 
 // Copied from https://github.com/dotnet/corefx/blob/b0751dcd4a419ba6731dcaa7d240a8a1946c934c/src/System.Text.Json/src/System/Text/Json/Serialization/ArrayBufferWriter.cs
 
-using System;
-using System.Buffers;
 using System.Diagnostics;
 
-namespace Microsoft.AspNetCore.Components.Server.BlazorPack
+namespace System.Buffers
 {
-    // Note: this is currently an internal class that will be replaced with a shared version.
-    internal sealed class ArrayBufferWriter<T> : IBufferWriter<T>, IDisposable
+    internal sealed class PooledArrayBufferWriter<T> : IBufferWriter<T>, IDisposable
     {
         private T[] _rentedBuffer;
         private int _index;
 
         private const int MinimumBufferSize = 256;
 
-        public ArrayBufferWriter()
+        public PooledArrayBufferWriter()
         {
             _rentedBuffer = ArrayPool<T>.Shared.Rent(MinimumBufferSize);
             _index = 0;
         }
 
-        public ArrayBufferWriter(int initialCapacity)
+        public PooledArrayBufferWriter(int initialCapacity)
         {
             if (initialCapacity <= 0)
             {
-                throw new ArgumentException(nameof(initialCapacity));
+                throw new ArgumentOutOfRangeException(nameof(initialCapacity));
             }
 
             _rentedBuffer = ArrayPool<T>.Shared.Rent(initialCapacity);
@@ -120,7 +117,9 @@ namespace Microsoft.AspNetCore.Components.Server.BlazorPack
             CheckIfDisposed();
 
             if (count < 0)
-                throw new ArgumentException(nameof(count));
+            {
+                throw new ArgumentOutOfRangeException(nameof(count));
+            }
 
             if (_index > _rentedBuffer.Length - count)
             {
@@ -152,7 +151,7 @@ namespace Microsoft.AspNetCore.Components.Server.BlazorPack
 
             if (sizeHint < 0)
             {
-                throw new ArgumentException(nameof(sizeHint));
+                throw new ArgumentOutOfRangeException(nameof(sizeHint));
             }
 
             if (sizeHint == 0)

+ 3 - 3
src/Shared/TaskToApm.cs

@@ -43,7 +43,7 @@ namespace System.Threading.Tasks
                 return;
             }
 
-            throw new ArgumentNullException();
+            throw new ArgumentNullException(nameof(asyncResult));
         }
 
         /// <summary>Processes an IAsyncResult returned by Begin.</summary>
@@ -55,7 +55,7 @@ namespace System.Threading.Tasks
                 return task.GetAwaiter().GetResult();
             }
 
-            throw new ArgumentNullException();
+            throw new ArgumentNullException(nameof(asyncResult));
         }
 
         /// <summary>Provides a simple IAsyncResult that wraps a Task.</summary>
@@ -118,4 +118,4 @@ namespace System.Threading.Tasks
             public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;
         }
     }
-}
+}

+ 1 - 1
src/Shared/runtime/Http2/Hpack/H2StaticTable.Http2.cs

@@ -21,7 +21,7 @@ namespace System.Net.Http.HPack
                 400 => 12,
                 404 => 13,
                 500 => 14,
-                _ => throw new ArgumentOutOfRangeException()
+                _ => throw new ArgumentOutOfRangeException(nameof(status))
             };
 
         private static readonly HeaderField[] s_staticDecoderTable = new HeaderField[]

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

@@ -218,7 +218,7 @@ namespace Microsoft.AspNetCore.SignalR.Client
         {
             _connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
             _protocol = protocol ?? throw new ArgumentNullException(nameof(protocol));
-            _endPoint = endPoint ?? throw new ArgumentException(nameof(endPoint));
+            _endPoint = endPoint ?? throw new ArgumentNullException(nameof(endPoint));
             _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
 
             _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
@@ -864,8 +864,10 @@ namespace Microsoft.AspNetCore.SignalR.Client
 
             Log.SendingMessage(_logger, hubMessage);
 
+#pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods
             // REVIEW: If a token is passed in and is canceled during FlushAsync it seems to break .Complete()...
             await connectionState.Connection.Transport.Output.FlushAsync();
+#pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods
             Log.MessageSent(_logger, hubMessage);
 
             // We've sent a message, so don't ping for a while

+ 29 - 28
src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs

@@ -278,44 +278,45 @@ namespace Microsoft.AspNetCore.SignalR.Client
             var inputChannel = await hubConnection.StreamAsChannelCoreAsync(methodName, typeof(TResult), args, cancellationToken);
             var outputChannel = Channel.CreateUnbounded<TResult>();
 
-            // Local function to provide a way to run async code as fire-and-forget
-            // The output channel is how we signal completion to the caller.
-            async Task RunChannel()
+            // Intentionally avoid passing the CancellationToken to RunChannel. The token is only meant to cancel the intial setup, not the enumeration.
+            _ = RunChannel(inputChannel, outputChannel);
+
+            return outputChannel.Reader;
+        }
+
+        // Function to provide a way to run async code as fire-and-forget
+        // The output channel is how we signal completion to the caller.
+        private static async Task RunChannel<TResult>(ChannelReader<object?> inputChannel, Channel<TResult> outputChannel)
+        {
+            try
             {
-                try
+                while (await inputChannel.WaitToReadAsync())
                 {
-                    while (await inputChannel.WaitToReadAsync())
+                    while (inputChannel.TryRead(out var item))
                     {
-                        while (inputChannel.TryRead(out var item))
+                        while (!outputChannel.Writer.TryWrite((TResult)item!))
                         {
-                            while (!outputChannel.Writer.TryWrite((TResult)item!))
+                            if (!await outputChannel.Writer.WaitToWriteAsync())
                             {
-                                if (!await outputChannel.Writer.WaitToWriteAsync())
-                                {
-                                    // Failed to write to the output channel because it was closed. Nothing really we can do but abort here.
-                                    return;
-                                }
+                                // Failed to write to the output channel because it was closed. Nothing really we can do but abort here.
+                                return;
                             }
                         }
                     }
-
-                    // Manifest any errors in the completion task
-                    await inputChannel.Completion;
-                }
-                catch (Exception ex)
-                {
-                    outputChannel.Writer.TryComplete(ex);
-                }
-                finally
-                {
-                    // This will safely no-op if the catch block above ran.
-                    outputChannel.Writer.TryComplete();
                 }
-            }
-
-            _ = RunChannel();
 
-            return outputChannel.Reader;
+                // Manifest any errors in the completion task
+                await inputChannel.Completion;
+            }
+            catch (Exception ex)
+            {
+                outputChannel.Writer.TryComplete(ex);
+            }
+            finally
+            {
+                // This will safely no-op if the catch block above ran.
+                outputChannel.Writer.TryComplete();
+            }
         }
     }
 }

+ 2 - 0
src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs

@@ -471,7 +471,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client
                     using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
                     {
                         response.EnsureSuccessStatusCode();
+#pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods
                         var responseBuffer = await response.Content.ReadAsByteArrayAsync();
+#pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods
                         var negotiateResponse = NegotiateProtocol.ParseResponse(responseBuffer);
                         if (!string.IsNullOrEmpty(negotiateResponse.Error))
                         {

+ 6 - 1
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LongPollingTransport.cs

@@ -188,9 +188,14 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
                     else
                     {
                         Log.ReceivedMessages(_logger);
+#if NETCOREAPP
+                        await response.Content.CopyToAsync(applicationStream, cancellationToken);
 
+#else
                         await response.Content.CopyToAsync(applicationStream);
-                        var flushResult = await _application.Output.FlushAsync();
+#endif
+
+                        var flushResult = await _application.Output.FlushAsync(cancellationToken);
 
                         // We canceled in the middle of applying back pressure
                         // or if the consumer is done

+ 1 - 1
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/SendUtils.cs

@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
             {
                 while (true)
                 {
-                    var result = await application.Input.ReadAsync();
+                    var result = await application.Input.ReadAsync(cancellationToken);
                     var buffer = result.Buffer;
 
                     try

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

@@ -41,7 +41,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
         {
             if (httpClient == null)
             {
-                throw new ArgumentNullException(nameof(_httpClient));
+                throw new ArgumentNullException(nameof(httpClient));
             }
 
             _httpClient = httpClient;
@@ -138,7 +138,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
             static void CancelReader(object? state) => ((PipeReader)state!).CancelPendingRead();
 
             using (response)
+#pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods
             using (var stream = await response.Content.ReadAsStreamAsync())
+#pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods
             {
                 var reader = PipeReader.Create(stream);
 
@@ -148,7 +150,8 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
                 {
                     while (true)
                     {
-                        var result = await reader.ReadAsync();
+                        // We rely on the CancelReader callback to cancel pending reads. Do not pass the token to ReadAsync since that would result in an exception on cancelation.
+                        var result = await reader.ReadAsync(default);
                         var buffer = result.Buffer;
                         var consumed = buffer.Start;
                         var examined = buffer.End;
@@ -173,7 +176,9 @@ namespace Microsoft.AspNetCore.Http.Connections.Client.Internal
                                     case ServerSentEventsMessageParser.ParseResult.Completed:
                                         Log.MessageToApplication(_logger, message!.Length);
 
-                                        flushResult = await _application.Output.WriteAsync(message);
+                                        // When cancellationToken is canceled the next line will cancel pending flushes on the pipe unblocking the await.
+                                        // Avoid passing the passed in context.
+                                        flushResult = await _application.Output.WriteAsync(message, default);
 
                                         _parser.Reset();
                                         break;

+ 6 - 8
src/SignalR/common/Http.Connections/src/Internal/Transports/ServerSentEventsServerTransport.cs

@@ -7,7 +7,6 @@ using System.Threading;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Http.Features;
 using Microsoft.Extensions.Logging;
-using Microsoft.Net.Http.Headers;
 
 namespace Microsoft.AspNetCore.Http.Connections.Internal.Transports
 {
@@ -32,7 +31,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Internal.Transports
             _logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Connections.Internal.Transports.ServerSentEventsTransport");
         }
 
-        public async Task ProcessRequestAsync(HttpContext context, CancellationToken token)
+        public async Task ProcessRequestAsync(HttpContext context, CancellationToken cancellationToken)
         {
             context.Response.ContentType = "text/event-stream";
             context.Response.Headers.CacheControl = "no-cache,no-store";
@@ -44,16 +43,15 @@ namespace Microsoft.AspNetCore.Http.Connections.Internal.Transports
 
             context.Response.Headers.ContentEncoding = "identity";
 
-            // Workaround for a Firefox bug where EventSource won't fire the open event
-            // until it receives some data
-            await context.Response.WriteAsync(":\r\n");
-            await context.Response.Body.FlushAsync();
-
             try
             {
+                // Workaround for a Firefox bug where EventSource won't fire the open event
+                // until it receives some data
+                await context.Response.WriteAsync(":\r\n", cancellationToken);
+                await context.Response.Body.FlushAsync(cancellationToken);
                 while (true)
                 {
-                    var result = await _application.ReadAsync(token);
+                    var result = await _application.ReadAsync(cancellationToken);
                     var buffer = result.Buffer;
 
                     try

+ 7 - 7
src/SignalR/common/Shared/MemoryBufferWriter.cs

@@ -140,10 +140,10 @@ namespace Microsoft.AspNetCore.Internal
             if (_completedSegments == null && _currentSegment is not null)
             {
                 // There is only one segment so write without awaiting.
-                return destination.WriteAsync(_currentSegment, 0, _position);
+                return destination.WriteAsync(_currentSegment, 0, _position, cancellationToken);
             }
 
-            return CopyToSlowAsync(destination);
+            return CopyToSlowAsync(destination, cancellationToken);
         }
 
         [MemberNotNull(nameof(_currentSegment))]
@@ -188,7 +188,7 @@ namespace Microsoft.AspNetCore.Internal
             _position = 0;
         }
 
-        private async Task CopyToSlowAsync(Stream destination)
+        private async Task CopyToSlowAsync(Stream destination, CancellationToken cancellationToken)
         {
             if (_completedSegments != null)
             {
@@ -198,9 +198,9 @@ namespace Microsoft.AspNetCore.Internal
                 {
                     var segment = _completedSegments[i];
 #if NETCOREAPP
-                    await destination.WriteAsync(segment.Buffer.AsMemory(0, segment.Length));
+                    await destination.WriteAsync(segment.Buffer.AsMemory(0, segment.Length), cancellationToken);
 #else
-                    await destination.WriteAsync(segment.Buffer, 0, segment.Length);
+                    await destination.WriteAsync(segment.Buffer, 0, segment.Length, cancellationToken);
 #endif
                 }
             }
@@ -208,9 +208,9 @@ namespace Microsoft.AspNetCore.Internal
             if (_currentSegment is not null)
             {
 #if NETCOREAPP
-                await destination.WriteAsync(_currentSegment.AsMemory(0, _position));
+                await destination.WriteAsync(_currentSegment.AsMemory(0, _position), cancellationToken);
 #else
-                await destination.WriteAsync(_currentSegment, 0, _position);
+                await destination.WriteAsync(_currentSegment, 0, _position, cancellationToken);
 #endif
             }
         }

+ 1 - 1
src/SignalR/common/Shared/PipeWriterStream.cs

@@ -73,7 +73,7 @@ namespace System.IO.Pipelines
             }
 
             _length += source.Length;
-            var task = _pipeWriter.WriteAsync(source);
+            var task = _pipeWriter.WriteAsync(source, cancellationToken);
             if (task.IsCompletedSuccessfully)
             {
                 // Cancellation can be triggered by PipeWriter.CancelPendingFlush

+ 1 - 1
src/SignalR/common/SignalR.Common/src/Protocol/HubMethodInvocationMessage.cs

@@ -50,7 +50,7 @@ namespace Microsoft.AspNetCore.SignalR.Protocol
         {
             if (string.IsNullOrEmpty(target))
             {
-                throw new ArgumentException(nameof(target));
+                throw new ArgumentNullException(nameof(target));
             }
 
             Target = target;

+ 4 - 0
src/SignalR/server/Core/src/HubConnectionContext.cs

@@ -174,7 +174,9 @@ namespace Microsoft.AspNetCore.SignalR
         internal ValueTask WriteAsync(HubMessage message, bool ignoreAbort, CancellationToken cancellationToken = default)
         {
             // Try to grab the lock synchronously, if we fail, go to the slower path
+#pragma warning disable CA2016 // This will always finish synchronously so we do not need to both with cancel
             if (!_writeLock.Wait(0))
+#pragma warning restore CA2016
             {
                 return new ValueTask(WriteSlowAsync(message, ignoreAbort, cancellationToken));
             }
@@ -217,8 +219,10 @@ namespace Microsoft.AspNetCore.SignalR
         public virtual ValueTask WriteAsync(SerializedHubMessage message, CancellationToken cancellationToken = default)
         {
             // Try to grab the lock synchronously, if we fail, go to the slower path
+#pragma warning disable CA2016 // This will always finish synchronously so we do not need to both with cancel
             if (!_writeLock.Wait(0))
             {
+#pragma warning restore CA2016
                 return new ValueTask(WriteSlowAsync(message, cancellationToken));
             }
 

+ 1 - 1
src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs

@@ -166,7 +166,7 @@ namespace Microsoft.AspNetCore.SignalR.StackExchangeRedis
             var connection = _connections[connectionId];
             if (connection != null)
             {
-                return connection.WriteAsync(new InvocationMessage(methodName, args)).AsTask();
+                return connection.WriteAsync(new InvocationMessage(methodName, args), cancellationToken).AsTask();
             }
 
             var message = _protocol.WriteInvocation(methodName, args);

+ 1 - 1
src/Testing/src/xunit/SkipOnHelixAttribute.cs

@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Testing
         {
             if (string.IsNullOrEmpty(issueUrl))
             {
-                throw new ArgumentException();
+                throw new ArgumentNullException(nameof(issueUrl));
             }
             IssueUrl = issueUrl;
         }

+ 1 - 1
src/Tools/dotnet-dev-certs/src/ReporterEventListener.cs

@@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.DeveloperCertificates.Tools
                 EventLevel.Warning => _reporter.Warn,
                 EventLevel.Informational => _reporter.Output,
                 EventLevel.Verbose => _reporter.Verbose,
-                _ => throw new ArgumentOutOfRangeException(nameof(eventData.Level), eventData.Level, $"The value of argument '{nameof(eventData.Level)}' ({eventData.Level}) is invalid for Enum type '{nameof(EventLevel)}'.")
+                _ => throw new ArgumentOutOfRangeException(nameof(eventData), eventData.Level, $"The value of argument '{nameof(eventData.Level)}' ({eventData.Level}) is invalid for Enum type '{nameof(EventLevel)}'.")
             };
             var message = string.Format(CultureInfo.InvariantCulture, eventData.Message ?? "", eventData.Payload?.ToArray() ?? Array.Empty<object>());
             report($"[{eventData.EventId}] " + message);