diff --git a/.editorconfig b/.editorconfig index 9627142199b5..14970459c258 100644 --- a/.editorconfig +++ b/.editorconfig @@ -92,6 +92,18 @@ dotnet_diagnostic.CA1305.severity = warning # CA1507: Use nameof to express symbol names dotnet_diagnostic.CA1507.severity = warning +# CA1510: Use ArgumentNullException throw helper +dotnet_diagnostic.CA1510.severity = warning + +# CA1511: Use ArgumentException throw helper +dotnet_diagnostic.CA1511.severity = warning + +# CA1512: Use ArgumentOutOfRangeException throw helper +dotnet_diagnostic.CA1512.severity = warning + +# CA1513: Use ObjectDisposedException throw helper +dotnet_diagnostic.CA1513.severity = warning + # CA1725: Parameter names should match base declaration dotnet_diagnostic.CA1725.severity = suggestion @@ -187,6 +199,18 @@ dotnet_diagnostic.CA1852.severity = warning # CA1854: Prefer the IDictionary.TryGetValue(TKey, out TValue) method dotnet_diagnostic.CA1854.severity = warning +# CA1855: Prefer 'Clear' over 'Fill' +dotnet_diagnostic.CA1855.severity = warning + +# CA1856: Incorrect usage of ConstantExpected attribute +dotnet_diagnostic.CA1856.severity = error + +# CA1857: A constant is expected for the parameter +dotnet_diagnostic.CA1857.severity = warning + +# CA1858: Use 'StartsWith' instead of 'IndexOf' +dotnet_diagnostic.CA1858.severity = warning + # CA2007: Consider calling ConfigureAwait on the awaited task dotnet_diagnostic.CA2007.severity = warning @@ -295,6 +319,14 @@ dotnet_diagnostic.IDE2000.severity = warning dotnet_diagnostic.CA1018.severity = suggestion # CA1507: Use nameof to express symbol names dotnet_diagnostic.CA1507.severity = suggestion +# CA1510: Use ArgumentNullException throw helper +dotnet_diagnostic.CA1510.severity = suggestion +# CA1511: Use ArgumentException throw helper +dotnet_diagnostic.CA1511.severity = suggestion +# CA1512: Use ArgumentOutOfRangeException throw helper +dotnet_diagnostic.CA1512.severity = suggestion +# CA1513: Use ObjectDisposedException throw helper +dotnet_diagnostic.CA1513.severity = suggestion # CA1802: Use literals where appropriate dotnet_diagnostic.CA1802.severity = suggestion # CA1805: Do not initialize unnecessarily @@ -333,6 +365,14 @@ dotnet_diagnostic.CA1847.severity = suggestion dotnet_diagnostic.CA1852.severity = suggestion # CA1854: Prefer the IDictionary.TryGetValue(TKey, out TValue) method dotnet_diagnostic.CA1854.severity = suggestion +# CA1855: Prefer 'Clear' over 'Fill' +dotnet_diagnostic.CA1855.severity = suggestion +# CA1856: Incorrect usage of ConstantExpected attribute +dotnet_diagnostic.CA1856.severity = suggestion +# CA1857: A constant is expected for the parameter +dotnet_diagnostic.CA1857.severity = suggestion +# CA1858: Use 'StartsWith' instead of 'IndexOf' +dotnet_diagnostic.CA1858.severity = suggestion # CA2007: Consider calling ConfigureAwait on the awaited task dotnet_diagnostic.CA2007.severity = suggestion # CA2008: Do not create tasks without passing a TaskScheduler diff --git a/Directory.Build.targets b/Directory.Build.targets index 1980cdcc77b2..5f4fbc649ae7 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -28,6 +28,12 @@ $(NoWarn);CS1591 + + + $(NoWarn);CA1510;CA1511;CA1512;CA1513 diff --git a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs index a77b07209cda..d40bf9354798 100644 --- a/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs +++ b/src/Antiforgery/src/AntiforgeryServiceCollectionExtensions.cs @@ -20,10 +20,7 @@ public static class AntiforgeryServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddAntiforgery(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddDataProtection(); @@ -57,15 +54,8 @@ public static IServiceCollection AddAntiforgery(this IServiceCollection services /// The so that additional calls can be chained. public static IServiceCollection AddAntiforgery(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); services.AddAntiforgery(); services.Configure(setupAction); diff --git a/src/Antiforgery/src/AntiforgeryTokenSet.cs b/src/Antiforgery/src/AntiforgeryTokenSet.cs index 6640f1e802f4..7524fb3a261c 100644 --- a/src/Antiforgery/src/AntiforgeryTokenSet.cs +++ b/src/Antiforgery/src/AntiforgeryTokenSet.cs @@ -21,10 +21,7 @@ public AntiforgeryTokenSet( string formFieldName, string? headerName) { - if (formFieldName == null) - { - throw new ArgumentNullException(nameof(formFieldName)); - } + ArgumentNullException.ThrowIfNull(formFieldName); RequestToken = requestToken; CookieToken = cookieToken; diff --git a/src/Antiforgery/src/Internal/AntiforgeryOptionsSetup.cs b/src/Antiforgery/src/Internal/AntiforgeryOptionsSetup.cs index f180d61605bc..dda99f7c55bd 100644 --- a/src/Antiforgery/src/Internal/AntiforgeryOptionsSetup.cs +++ b/src/Antiforgery/src/Internal/AntiforgeryOptionsSetup.cs @@ -20,10 +20,7 @@ public AntiforgeryOptionsSetup(IOptions dataProtectionOpt public void Configure(AntiforgeryOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.Cookie.Name == null) { diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgery.cs b/src/Antiforgery/src/Internal/DefaultAntiforgery.cs index b90c62793a24..129d1f7e3104 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgery.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgery.cs @@ -39,10 +39,7 @@ public DefaultAntiforgery( /// public AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); CheckSSLConfig(httpContext); @@ -79,10 +76,7 @@ public AntiforgeryTokenSet GetAndStoreTokens(HttpContext httpContext) /// public AntiforgeryTokenSet GetTokens(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); CheckSSLConfig(httpContext); @@ -93,10 +87,7 @@ public AntiforgeryTokenSet GetTokens(HttpContext httpContext) /// public async Task IsRequestValidAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); CheckSSLConfig(httpContext); @@ -151,10 +142,7 @@ public async Task IsRequestValidAsync(HttpContext httpContext) /// public async Task ValidateRequestAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); CheckSSLConfig(httpContext); @@ -220,10 +208,7 @@ private void ValidateTokens(HttpContext httpContext, AntiforgeryTokenSet antifor /// public void SetCookieTokenAndHeader(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); CheckSSLConfig(httpContext); diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs index 782b0755767c..06a08914924d 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenGenerator.cs @@ -36,15 +36,8 @@ public AntiforgeryToken GenerateRequestToken( HttpContext httpContext, AntiforgeryToken cookieToken) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (cookieToken == null) - { - throw new ArgumentNullException(nameof(cookieToken)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(cookieToken); if (!IsCookieTokenValid(cookieToken)) { @@ -112,10 +105,7 @@ public bool TryValidateTokenSet( AntiforgeryToken requestToken, [NotNullWhen(false)] out string? message) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); if (cookieToken == null) { diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs index f269a5968c12..0cc346b0de42 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenSerializer.cs @@ -19,15 +19,8 @@ public DefaultAntiforgeryTokenSerializer( IDataProtectionProvider provider, ObjectPool pool) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (pool == null) - { - throw new ArgumentNullException(nameof(pool)); - } + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(pool); _cryptoSystem = provider.CreateProtector(Purpose); _pool = pool; @@ -131,10 +124,7 @@ public AntiforgeryToken Deserialize(string serializedToken) public string Serialize(AntiforgeryToken token) { - if (token == null) - { - throw new ArgumentNullException(nameof(token)); - } + ArgumentNullException.ThrowIfNull(token); var serializationContext = _pool.Get(); diff --git a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs index 7821a303df25..b57a40f162a6 100644 --- a/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs +++ b/src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs @@ -14,10 +14,7 @@ internal sealed class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore public DefaultAntiforgeryTokenStore(IOptions optionsAccessor) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } + ArgumentNullException.ThrowIfNull(optionsAccessor); _options = optionsAccessor.Value; } diff --git a/src/Azure/AzureAppServicesIntegration/src/AppServicesWebHostBuilderExtensions.cs b/src/Azure/AzureAppServicesIntegration/src/AppServicesWebHostBuilderExtensions.cs index ac6a3426a78c..7e20e89d5f45 100644 --- a/src/Azure/AzureAppServicesIntegration/src/AppServicesWebHostBuilderExtensions.cs +++ b/src/Azure/AzureAppServicesIntegration/src/AppServicesWebHostBuilderExtensions.cs @@ -17,10 +17,7 @@ public static class AppServicesWebHostBuilderExtensions /// public static IWebHostBuilder UseAzureAppServices(this IWebHostBuilder hostBuilder) { - if (hostBuilder == null) - { - throw new ArgumentNullException(nameof(hostBuilder)); - } + ArgumentNullException.ThrowIfNull(hostBuilder); #pragma warning disable 618 hostBuilder.ConfigureLogging(builder => builder.AddAzureWebAppDiagnostics()); #pragma warning restore 618 diff --git a/src/Components/Authorization/src/AuthenticationStateProvider.cs b/src/Components/Authorization/src/AuthenticationStateProvider.cs index 880f36e938d1..ad57e6d903ca 100644 --- a/src/Components/Authorization/src/AuthenticationStateProvider.cs +++ b/src/Components/Authorization/src/AuthenticationStateProvider.cs @@ -26,10 +26,7 @@ public abstract class AuthenticationStateProvider /// A that supplies the updated . protected void NotifyAuthenticationStateChanged(Task task) { - if (task == null) - { - throw new ArgumentNullException(nameof(task)); - } + ArgumentNullException.ThrowIfNull(task); AuthenticationStateChanged?.Invoke(task); } diff --git a/src/Components/Components/src/BindElementAttribute.cs b/src/Components/Components/src/BindElementAttribute.cs index 7539813d0979..41bcd831393e 100644 --- a/src/Components/Components/src/BindElementAttribute.cs +++ b/src/Components/Components/src/BindElementAttribute.cs @@ -18,20 +18,9 @@ public sealed class BindElementAttribute : Attribute /// The name of an attribute that will register an associated change event. public BindElementAttribute(string element, string? suffix, string valueAttribute, string changeAttribute) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } - - if (valueAttribute == null) - { - throw new ArgumentNullException(nameof(valueAttribute)); - } - - if (changeAttribute == null) - { - throw new ArgumentNullException(nameof(changeAttribute)); - } + ArgumentNullException.ThrowIfNull(element); + ArgumentNullException.ThrowIfNull(valueAttribute); + ArgumentNullException.ThrowIfNull(changeAttribute); Element = element; ValueAttribute = valueAttribute; diff --git a/src/Components/Components/src/CascadingTypeParameterAttribute.cs b/src/Components/Components/src/CascadingTypeParameterAttribute.cs index afae8535e68d..e74121dcf3bf 100644 --- a/src/Components/Components/src/CascadingTypeParameterAttribute.cs +++ b/src/Components/Components/src/CascadingTypeParameterAttribute.cs @@ -17,10 +17,7 @@ public sealed class CascadingTypeParameterAttribute : Attribute /// The name of the type parameter. public CascadingTypeParameterAttribute(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; } diff --git a/src/Components/Components/src/Dispatcher.cs b/src/Components/Components/src/Dispatcher.cs index 074b0ef1f049..14de2d96ee0c 100644 --- a/src/Components/Components/src/Dispatcher.cs +++ b/src/Components/Components/src/Dispatcher.cs @@ -85,10 +85,7 @@ public void AssertAccess() /// The . protected void OnUnhandledException(UnhandledExceptionEventArgs e) { - if (e is null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); UnhandledException?.Invoke(this, e); } diff --git a/src/Components/Components/src/ErrorBoundaryBase.cs b/src/Components/Components/src/ErrorBoundaryBase.cs index f0d78c42f959..d58de4e33c20 100644 --- a/src/Components/Components/src/ErrorBoundaryBase.cs +++ b/src/Components/Components/src/ErrorBoundaryBase.cs @@ -56,11 +56,7 @@ public void Recover() void IErrorBoundary.HandleException(Exception exception) { - if (exception is null) - { - // This would be a framework bug if it happened. It should not be possible. - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); // If rendering the error content itself causes an error, then re-rendering on error risks creating an // infinite error loop. Unfortunately it's very hard to distinguish whether the error source is "child content" diff --git a/src/Components/Components/src/EventCallbackFactory.cs b/src/Components/Components/src/EventCallbackFactory.cs index 4e23584e4ba6..11c637a75e5d 100644 --- a/src/Components/Components/src/EventCallbackFactory.cs +++ b/src/Components/Components/src/EventCallbackFactory.cs @@ -20,10 +20,7 @@ public sealed class EventCallbackFactory [EditorBrowsable(EditorBrowsableState.Never)] public EventCallback Create(object receiver, EventCallback callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return callback; } @@ -37,10 +34,7 @@ public EventCallback Create(object receiver, EventCallback callback) /// The . public EventCallback Create(object receiver, Action callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -54,10 +48,7 @@ public EventCallback Create(object receiver, Action callback) /// The . public EventCallback Create(object receiver, Action callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -71,10 +62,7 @@ public EventCallback Create(object receiver, Action callback) /// The . public EventCallback Create(object receiver, Func callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -88,10 +76,7 @@ public EventCallback Create(object receiver, Func callback) /// The . public EventCallback Create(object receiver, Func callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -105,10 +90,7 @@ public EventCallback Create(object receiver, Func callback) [EditorBrowsable(EditorBrowsableState.Never)] public EventCallback Create(object receiver, EventCallback callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return new EventCallback(callback.Receiver, callback.Delegate); } @@ -122,10 +104,7 @@ public EventCallback Create(object receiver, EventCallback callb [EditorBrowsable(EditorBrowsableState.Never)] public EventCallback Create(object receiver, EventCallback callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return callback; } @@ -139,10 +118,7 @@ public EventCallback Create(object receiver, EventCallbackThe . public EventCallback Create(object receiver, Action callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -156,10 +132,7 @@ public EventCallback Create(object receiver, Action callback) /// The . public EventCallback Create(object receiver, Action callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -173,10 +146,7 @@ public EventCallback Create(object receiver, Action call /// The . public EventCallback Create(object receiver, Func callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } @@ -190,10 +160,7 @@ public EventCallback Create(object receiver, Func callback /// The . public EventCallback Create(object receiver, Func callback) { - if (receiver == null) - { - throw new ArgumentNullException(nameof(receiver)); - } + ArgumentNullException.ThrowIfNull(receiver); return CreateCore(receiver, callback); } diff --git a/src/Components/Components/src/EventCallbackFactoryEventArgsExtensions.cs b/src/Components/Components/src/EventCallbackFactoryEventArgsExtensions.cs index a4eae8e318ef..e70dac2547f2 100644 --- a/src/Components/Components/src/EventCallbackFactoryEventArgsExtensions.cs +++ b/src/Components/Components/src/EventCallbackFactoryEventArgsExtensions.cs @@ -18,10 +18,7 @@ public static class EventCallbackFactoryEventArgsExtensions /// The . public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -36,10 +33,7 @@ public static EventCallback Create(this EventCallbackFactory factory, /// The . public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -54,10 +48,7 @@ public static EventCallback Create(this EventCallbackFactory factory, /// The . public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -72,10 +63,7 @@ public static EventCallback Create(this EventCallbackFactory fa /// The . public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } diff --git a/src/Components/Components/src/EventHandlerAttribute.cs b/src/Components/Components/src/EventHandlerAttribute.cs index 81a68bb56565..7d149496b034 100644 --- a/src/Components/Components/src/EventHandlerAttribute.cs +++ b/src/Components/Components/src/EventHandlerAttribute.cs @@ -27,15 +27,8 @@ public EventHandlerAttribute(string attributeName, Type eventArgsType) : this(at /// public EventHandlerAttribute(string attributeName, Type eventArgsType, bool enableStopPropagation, bool enablePreventDefault) { - if (attributeName == null) - { - throw new ArgumentNullException(nameof(attributeName)); - } - - if (eventArgsType == null) - { - throw new ArgumentNullException(nameof(eventArgsType)); - } + ArgumentNullException.ThrowIfNull(attributeName); + ArgumentNullException.ThrowIfNull(eventArgsType); AttributeName = attributeName; EventArgsType = eventArgsType; diff --git a/src/Components/Components/src/NavigationManager.cs b/src/Components/Components/src/NavigationManager.cs index 7e71bf0110cd..1c17ac7d9025 100644 --- a/src/Components/Components/src/NavigationManager.cs +++ b/src/Components/Components/src/NavigationManager.cs @@ -173,15 +173,8 @@ protected virtual void NavigateToCore([StringSyntax(StringSyntaxAttribute.Uri)] protected void Initialize(string baseUri, string uri) { // Make sure it's possible/safe to call this method from constructors of derived classes. - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - - if (baseUri == null) - { - throw new ArgumentNullException(nameof(baseUri)); - } + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(baseUri); if (_isInitialized) { diff --git a/src/Components/Components/src/NavigationManagerExtensions.cs b/src/Components/Components/src/NavigationManagerExtensions.cs index 22949eceec81..24746270c942 100644 --- a/src/Components/Components/src/NavigationManagerExtensions.cs +++ b/src/Components/Components/src/NavigationManagerExtensions.cs @@ -521,10 +521,7 @@ public static string GetUriWithQueryParameter(this NavigationManager navigationM /// public static string GetUriWithQueryParameter(this NavigationManager navigationManager, string name, string? value) { - if (navigationManager is null) - { - throw new ArgumentNullException(nameof(navigationManager)); - } + ArgumentNullException.ThrowIfNull(navigationManager); if (string.IsNullOrEmpty(name)) { @@ -561,15 +558,8 @@ public static string GetUriWithQueryParameters( string uri, IReadOnlyDictionary parameters) { - if (navigationManager is null) - { - throw new ArgumentNullException(nameof(navigationManager)); - } - - if (uri is null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(navigationManager); + ArgumentNullException.ThrowIfNull(uri); if (!TryRebuildExistingQueryFromUri( uri, @@ -752,7 +742,7 @@ private static bool TryRebuildExistingQueryFromUri( if (queryStartIndex < 0) { - + existingQueryStringEnumerable = default; uriWithoutQueryStringAndHash = hashStartIndex < 0 ? uri : uri.AsSpan(0, hashStartIndex); newQueryStringBuilder = new(uriWithoutQueryStringAndHash); diff --git a/src/Components/Components/src/ParameterView.cs b/src/Components/Components/src/ParameterView.cs index 23b989e98507..544ef27ccc28 100644 --- a/src/Components/Components/src/ParameterView.cs +++ b/src/Components/Components/src/ParameterView.cs @@ -304,10 +304,7 @@ public static ParameterView FromDictionary(IDictionary paramete /// An object that has a public writable property matching each parameter's name and type. public void SetParameterProperties(object target) { - if (target is null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); ComponentProperties.SetProperties(this, target); } diff --git a/src/Components/Components/src/PersistentComponentState.cs b/src/Components/Components/src/PersistentComponentState.cs index 27bdf872d7c8..c7dd82965e43 100644 --- a/src/Components/Components/src/PersistentComponentState.cs +++ b/src/Components/Components/src/PersistentComponentState.cs @@ -44,10 +44,7 @@ internal void InitializeExistingState(IDictionary existingState) /// A subscription that can be used to unregister the callback when disposed. public PersistingComponentStateSubscription RegisterOnPersisting(Func callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); _registeredCallbacks.Add(callback); @@ -63,10 +60,7 @@ public PersistingComponentStateSubscription RegisterOnPersisting(Func call [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")] public void PersistAsJson<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(string key, TValue instance) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (!PersistingState) { @@ -93,10 +87,7 @@ public PersistingComponentStateSubscription RegisterOnPersisting(Func call [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")] public bool TryTakeFromJson<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(string key, [MaybeNullWhen(false)] out TValue? instance) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (TryTake(key, out var data)) { @@ -113,10 +104,7 @@ public PersistingComponentStateSubscription RegisterOnPersisting(Func call private bool TryTake(string key, out byte[]? value) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (_existingState == null) { diff --git a/src/Components/Components/src/Reflection/ComponentProperties.cs b/src/Components/Components/src/Reflection/ComponentProperties.cs index ecf5eafc6666..dd0df1e094cd 100644 --- a/src/Components/Components/src/Reflection/ComponentProperties.cs +++ b/src/Components/Components/src/Reflection/ComponentProperties.cs @@ -22,10 +22,7 @@ private static readonly ConcurrentDictionary _cachedWriter public static void SetProperties(in ParameterView parameters, object target) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); var targetType = target.GetType(); if (!_cachedWritersByType.TryGetValue(targetType, out var writers)) diff --git a/src/Components/Components/src/RenderTree/Renderer.cs b/src/Components/Components/src/RenderTree/Renderer.cs index c1fc2b4e643f..b0e8ad00e7b0 100644 --- a/src/Components/Components/src/RenderTree/Renderer.cs +++ b/src/Components/Components/src/RenderTree/Renderer.cs @@ -77,20 +77,9 @@ public Renderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory) /// The . public Renderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, IComponentActivator componentActivator) { - if (serviceProvider is null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } - - if (loggerFactory is null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (componentActivator is null) - { - throw new ArgumentNullException(nameof(componentActivator)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(componentActivator); _serviceProvider = serviceProvider; // Would normally use ILogger here to get the benefit of the string name being cached but this is a public ctor that diff --git a/src/Components/Components/src/RouteAttribute.cs b/src/Components/Components/src/RouteAttribute.cs index 88a24b879d20..58d3c2500dc9 100644 --- a/src/Components/Components/src/RouteAttribute.cs +++ b/src/Components/Components/src/RouteAttribute.cs @@ -15,10 +15,7 @@ public sealed class RouteAttribute : Attribute /// The route template. public RouteAttribute(string template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); Template = template; } diff --git a/src/Components/Components/src/Routing/RouteData.cs b/src/Components/Components/src/Routing/RouteData.cs index 9da66388c6ee..f3e2bdedc107 100644 --- a/src/Components/Components/src/Routing/RouteData.cs +++ b/src/Components/Components/src/Routing/RouteData.cs @@ -19,10 +19,7 @@ public sealed class RouteData /// The route parameter values extracted from the matched route. public RouteData([DynamicallyAccessedMembers(Component)] Type pageType, IReadOnlyDictionary routeValues) { - if (pageType == null) - { - throw new ArgumentNullException(nameof(pageType)); - } + ArgumentNullException.ThrowIfNull(pageType); if (!typeof(IComponent).IsAssignableFrom(pageType)) { diff --git a/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs b/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs index 7a926e0ee8fe..2fb2a68b6d0d 100644 --- a/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs +++ b/src/Components/Forms/src/EditContextDataAnnotationsExtensions.cs @@ -46,10 +46,7 @@ public static IDisposable EnableDataAnnotationsValidation(this EditContext editC /// A disposable object whose disposal will remove DataAnnotations validation support from the . public static IDisposable EnableDataAnnotationsValidation(this EditContext editContext, IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); return new DataAnnotationsEventSubscriptions(editContext, serviceProvider); } diff --git a/src/Components/Forms/src/FieldIdentifier.cs b/src/Components/Forms/src/FieldIdentifier.cs index fafe46fb14be..25c754b8a2ca 100644 --- a/src/Components/Forms/src/FieldIdentifier.cs +++ b/src/Components/Forms/src/FieldIdentifier.cs @@ -19,10 +19,7 @@ namespace Microsoft.AspNetCore.Components.Forms; /// The field . public static FieldIdentifier Create(Expression> accessor) { - if (accessor == null) - { - throw new ArgumentNullException(nameof(accessor)); - } + ArgumentNullException.ThrowIfNull(accessor); ParseAccessor(accessor, out var model, out var fieldName); return new FieldIdentifier(model, fieldName); @@ -35,10 +32,7 @@ public static FieldIdentifier Create(Expression> accessor) /// The name of the editable field. public FieldIdentifier(object model, string fieldName) { - if (model is null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); if (model.GetType().IsValueType) { diff --git a/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs b/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs index 1946d117a9d0..7944a9056aed 100644 --- a/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs +++ b/src/Components/Server/src/Builder/ComponentEndpointRouteBuilderExtensions.cs @@ -22,10 +22,7 @@ public static class ComponentEndpointRouteBuilderExtensions /// The . public static ComponentEndpointConventionBuilder MapBlazorHub(this IEndpointRouteBuilder endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); return endpoints.MapBlazorHub(ComponentHub.DefaultPath); } @@ -40,15 +37,8 @@ public static ComponentEndpointConventionBuilder MapBlazorHub( this IEndpointRouteBuilder endpoints, string path) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(path); return endpoints.MapBlazorHub(path, configureOptions: _ => { }); } @@ -63,15 +53,8 @@ public static ComponentEndpointConventionBuilder MapBlazorHub( this IEndpointRouteBuilder endpoints, Action configureOptions) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(configureOptions); return endpoints.MapBlazorHub(ComponentHub.DefaultPath, configureOptions); } @@ -88,20 +71,9 @@ public static ComponentEndpointConventionBuilder MapBlazorHub( string path, Action configureOptions) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(configureOptions); var hubEndpoint = endpoints.MapHub(path, configureOptions); diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 6156b407a282..6e5374bc54ef 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -599,10 +599,12 @@ private void AssertInitialized() private void AssertNotDisposed() { +#pragma warning disable CA1513 // Use ObjectDisposedException throw helper if (_disposed) { throw new ObjectDisposedException(objectName: null); } +#pragma warning restore CA1513 // Use ObjectDisposedException throw helper } // We want to notify the client if it's still connected, and then tear-down the circuit. diff --git a/src/Components/Server/src/Circuits/RevalidatingServerAuthenticationStateProvider.cs b/src/Components/Server/src/Circuits/RevalidatingServerAuthenticationStateProvider.cs index a0b0b172a400..879520ff25be 100644 --- a/src/Components/Server/src/Circuits/RevalidatingServerAuthenticationStateProvider.cs +++ b/src/Components/Server/src/Circuits/RevalidatingServerAuthenticationStateProvider.cs @@ -23,10 +23,7 @@ public abstract class RevalidatingServerAuthenticationStateProvider /// A logger factory. public RevalidatingServerAuthenticationStateProvider(ILoggerFactory loggerFactory) { - if (loggerFactory is null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); diff --git a/src/Components/Server/src/DependencyInjection/ServerSideBlazorBuilderExtensions.cs b/src/Components/Server/src/DependencyInjection/ServerSideBlazorBuilderExtensions.cs index d305f6eebb6a..633db966942d 100644 --- a/src/Components/Server/src/DependencyInjection/ServerSideBlazorBuilderExtensions.cs +++ b/src/Components/Server/src/DependencyInjection/ServerSideBlazorBuilderExtensions.cs @@ -19,15 +19,8 @@ public static class ServerSideBlazorBuilderExtensions /// The . public static IServerSideBlazorBuilder AddCircuitOptions(this IServerSideBlazorBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure(configure); @@ -42,15 +35,8 @@ public static IServerSideBlazorBuilder AddCircuitOptions(this IServerSideBlazorB /// The . public static IServerSideBlazorBuilder AddHubOptions(this IServerSideBlazorBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure>(configure); diff --git a/src/Components/Web/src/BindInputElementAttribute.cs b/src/Components/Web/src/BindInputElementAttribute.cs index 6ed009a3fdb1..0169a4ceceb7 100644 --- a/src/Components/Web/src/BindInputElementAttribute.cs +++ b/src/Components/Web/src/BindInputElementAttribute.cs @@ -26,15 +26,8 @@ public sealed class BindInputElementAttribute : Attribute /// public BindInputElementAttribute(string? type, string? suffix, string? valueAttribute, string? changeAttribute, bool isInvariantCulture, string? format) { - if (valueAttribute == null) - { - throw new ArgumentNullException(nameof(valueAttribute)); - } - - if (changeAttribute == null) - { - throw new ArgumentNullException(nameof(changeAttribute)); - } + ArgumentNullException.ThrowIfNull(valueAttribute); + ArgumentNullException.ThrowIfNull(changeAttribute); Type = type; Suffix = suffix; diff --git a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs index 1d38b84df952..5be4a63d99e4 100644 --- a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs +++ b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs @@ -46,10 +46,7 @@ public static string FieldCssClass(this EditContext editContext, in FieldIdentif /// The . public static void SetFieldCssClassProvider(this EditContext editContext, FieldCssClassProvider fieldCssClassProvider) { - if (fieldCssClassProvider is null) - { - throw new ArgumentNullException(nameof(fieldCssClassProvider)); - } + ArgumentNullException.ThrowIfNull(fieldCssClassProvider); editContext.Properties[FieldCssClassProviderKey] = fieldCssClassProvider; } diff --git a/src/Components/Web/src/Web/WebEventCallbackFactoryEventArgsExtensions.cs b/src/Components/Web/src/Web/WebEventCallbackFactoryEventArgsExtensions.cs index 076057265e2a..4c34865354ea 100644 --- a/src/Components/Web/src/Web/WebEventCallbackFactoryEventArgsExtensions.cs +++ b/src/Components/Web/src/Web/WebEventCallbackFactoryEventArgsExtensions.cs @@ -19,10 +19,7 @@ public static class WebEventCallbackFactoryEventArgsExtensions [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -38,10 +35,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -57,10 +51,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -76,10 +67,7 @@ public static EventCallback Create(this EventCallbackFactory fact [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -95,10 +83,7 @@ public static EventCallback Create(this EventCallbackFactory fact [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -114,10 +99,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -133,10 +115,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -152,10 +131,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -171,10 +147,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -190,10 +163,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -209,10 +179,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -228,10 +195,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -246,10 +210,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -265,10 +226,7 @@ public static EventCallback Create(this EventCallbackFactory f [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -284,10 +242,7 @@ public static EventCallback Create(this EventCallbackFactory f [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -303,10 +258,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -322,10 +274,7 @@ public static EventCallback Create(this EventCallbackFactory [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -341,10 +290,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -360,10 +306,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Action callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } @@ -379,10 +322,7 @@ public static EventCallback Create(this EventCallbackFactory fac [Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")] public static EventCallback Create(this EventCallbackFactory factory, object receiver, Func callback) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.Create(receiver, callback); } diff --git a/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs b/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs index 5ccdabe25c8a..c7292d991b76 100644 --- a/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs +++ b/src/Components/WebAssembly/Server/src/ComponentsWebAssemblyApplicationBuilderExtensions.cs @@ -28,10 +28,7 @@ public static class ComponentsWebAssemblyApplicationBuilderExtensions /// The public static IApplicationBuilder UseBlazorFrameworkFiles(this IApplicationBuilder builder, PathString pathPrefix) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); var webHostEnvironment = builder.ApplicationServices.GetRequiredService(); diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs index 1f0cc253880d..ea7057399eaa 100644 --- a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs +++ b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/AuthorizationMessageHandler.cs @@ -102,10 +102,7 @@ public AuthorizationMessageHandler ConfigureHandler( throw new InvalidOperationException("Handler already configured."); } - if (authorizedUrls == null) - { - throw new ArgumentNullException(nameof(authorizedUrls)); - } + ArgumentNullException.ThrowIfNull(authorizedUrls); var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray(); if (uris.Length == 0) diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs index 274ceafa4bd3..6eb2ac2a79bc 100644 --- a/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs +++ b/src/Components/WebAssembly/WebAssembly.Authentication/src/Services/RemoteAuthenticationService.cs @@ -170,10 +170,7 @@ public virtual async ValueTask RequestAccessToken() public virtual async ValueTask RequestAccessToken(AccessTokenRequestOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); await EnsureAuthService(); var result = await JsRuntime.InvokeAsync("AuthenticationService.getAccessToken", options); diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMapping.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMapping.cs index 101aed8ab87c..28949756fe5e 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMapping.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMapping.cs @@ -19,10 +19,7 @@ public readonly struct RootComponentMapping /// The DOM element selector or component registration id for the component. public RootComponentMapping([DynamicallyAccessedMembers(Component)] Type componentType, string selector) { - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(componentType); if (!typeof(IComponent).IsAssignableFrom(componentType)) { @@ -31,10 +28,7 @@ public RootComponentMapping([DynamicallyAccessedMembers(Component)] Type compone nameof(componentType)); } - if (selector is null) - { - throw new ArgumentNullException(nameof(selector)); - } + ArgumentNullException.ThrowIfNull(selector); ComponentType = componentType; Selector = selector; diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMappingCollection.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMappingCollection.cs index d0cf493ddb0e..61a284926d6a 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMappingCollection.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/RootComponentMappingCollection.cs @@ -23,10 +23,7 @@ public class RootComponentMappingCollection : Collection, /// The DOM element selector. public void Add<[DynamicallyAccessedMembers(Component)] TComponent>(string selector) where TComponent : IComponent { - if (selector is null) - { - throw new ArgumentNullException(nameof(selector)); - } + ArgumentNullException.ThrowIfNull(selector); Add(new RootComponentMapping(typeof(TComponent), selector)); } @@ -49,15 +46,8 @@ public void Add([DynamicallyAccessedMembers(Component)] Type componentType, stri /// The parameters to the root component. public void Add([DynamicallyAccessedMembers(Component)] Type componentType, string selector, ParameterView parameters) { - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } - - if (selector is null) - { - throw new ArgumentNullException(nameof(selector)); - } + ArgumentNullException.ThrowIfNull(componentType); + ArgumentNullException.ThrowIfNull(selector); Add(new RootComponentMapping(componentType, selector, parameters)); } @@ -68,10 +58,7 @@ public void Add([DynamicallyAccessedMembers(Component)] Type componentType, stri /// The items to add. public void AddRange(IEnumerable items) { - if (items is null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); foreach (var item in items) { diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs index 8b03d2d2da5b..11f07020f3e6 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs @@ -227,10 +227,7 @@ private WebAssemblyHostEnvironment InitializeEnvironment(IJSUnmarshalledRuntime /// public void ConfigureContainer(IServiceProviderFactory factory, Action? configure = null) where TBuilder : notnull { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); _createServiceProvider = () => { diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs index 3144587d8d85..3de2058d0789 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostConfiguration.cs @@ -142,10 +142,7 @@ private void RaiseChanged() /// The same . public IConfigurationBuilder Add(IConfigurationSource source) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); // Adds this source and its associated provider to the source // and provider references in this class. We make sure to load diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostEnvironmentExtensions.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostEnvironmentExtensions.cs index 49c701964681..a0dbb40a1142 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostEnvironmentExtensions.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostEnvironmentExtensions.cs @@ -15,10 +15,7 @@ public static class WebAssemblyHostEnvironmentExtensions /// True if the environment name is Development, otherwise false. public static bool IsDevelopment(this IWebAssemblyHostEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment("Development"); } @@ -30,10 +27,7 @@ public static bool IsDevelopment(this IWebAssemblyHostEnvironment hostingEnviron /// True if the environment name is Staging, otherwise false. public static bool IsStaging(this IWebAssemblyHostEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment("Staging"); } @@ -45,10 +39,7 @@ public static bool IsStaging(this IWebAssemblyHostEnvironment hostingEnvironment /// True if the environment name is Production, otherwise false. public static bool IsProduction(this IWebAssemblyHostEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment("Production"); } @@ -63,10 +54,7 @@ public static bool IsEnvironment( this IWebAssemblyHostEnvironment hostingEnvironment, string environmentName) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return string.Equals( hostingEnvironment.Environment, diff --git a/src/Components/WebAssembly/WebAssembly/src/Http/WebAssemblyHttpRequestMessageExtensions.cs b/src/Components/WebAssembly/WebAssembly/src/Http/WebAssemblyHttpRequestMessageExtensions.cs index 73b43614de1b..ef353f5395a0 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Http/WebAssemblyHttpRequestMessageExtensions.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Http/WebAssemblyHttpRequestMessageExtensions.cs @@ -24,10 +24,7 @@ public static class WebAssemblyHttpRequestMessageExtensions /// public static HttpRequestMessage SetBrowserRequestCredentials(this HttpRequestMessage requestMessage, BrowserRequestCredentials requestCredentials) { - if (requestMessage is null) - { - throw new ArgumentNullException(nameof(requestMessage)); - } + ArgumentNullException.ThrowIfNull(requestMessage); var stringOption = requestCredentials switch { @@ -51,10 +48,7 @@ public static HttpRequestMessage SetBrowserRequestCredentials(this HttpRequestMe /// public static HttpRequestMessage SetBrowserRequestCache(this HttpRequestMessage requestMessage, BrowserRequestCache requestCache) { - if (requestMessage is null) - { - throw new ArgumentNullException(nameof(requestMessage)); - } + ArgumentNullException.ThrowIfNull(requestMessage); var stringOption = requestCache switch { @@ -81,10 +75,7 @@ public static HttpRequestMessage SetBrowserRequestCache(this HttpRequestMessage /// public static HttpRequestMessage SetBrowserRequestMode(this HttpRequestMessage requestMessage, BrowserRequestMode requestMode) { - if (requestMessage is null) - { - throw new ArgumentNullException(nameof(requestMessage)); - } + ArgumentNullException.ThrowIfNull(requestMessage); var stringOption = requestMode switch { @@ -122,10 +113,7 @@ public static HttpRequestMessage SetBrowserRequestIntegrity(this HttpRequestMess /// public static HttpRequestMessage SetBrowserRequestOption(this HttpRequestMessage requestMessage, string name, object value) { - if (requestMessage is null) - { - throw new ArgumentNullException(nameof(requestMessage)); - } + ArgumentNullException.ThrowIfNull(requestMessage); IDictionary fetchOptions; if (requestMessage.Options.TryGetValue(FetchRequestOptionsKey, out var entry)) @@ -155,10 +143,7 @@ public static HttpRequestMessage SetBrowserRequestOption(this HttpRequestMessage /// public static HttpRequestMessage SetBrowserResponseStreamingEnabled(this HttpRequestMessage requestMessage, bool streamingEnabled) { - if (requestMessage is null) - { - throw new ArgumentNullException(nameof(requestMessage)); - } + ArgumentNullException.ThrowIfNull(requestMessage); requestMessage.Options.Set(WebAssemblyEnableStreamingResponseKey, streamingEnabled); diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/NullDispatcher.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/NullDispatcher.cs index ecf4d98245d1..0bef674afd84 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/NullDispatcher.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/NullDispatcher.cs @@ -15,10 +15,7 @@ private NullDispatcher() public override Task InvokeAsync(Action workItem) { - if (workItem is null) - { - throw new ArgumentNullException(nameof(workItem)); - } + ArgumentNullException.ThrowIfNull(workItem); workItem(); return Task.CompletedTask; @@ -26,30 +23,21 @@ public override Task InvokeAsync(Action workItem) public override Task InvokeAsync(Func workItem) { - if (workItem is null) - { - throw new ArgumentNullException(nameof(workItem)); - } + ArgumentNullException.ThrowIfNull(workItem); return workItem(); } public override Task InvokeAsync(Func workItem) { - if (workItem is null) - { - throw new ArgumentNullException(nameof(workItem)); - } + ArgumentNullException.ThrowIfNull(workItem); return Task.FromResult(workItem()); } public override Task InvokeAsync(Func> workItem) { - if (workItem is null) - { - throw new ArgumentNullException(nameof(workItem)); - } + ArgumentNullException.ThrowIfNull(workItem); return workItem(); } diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs index c5a658be60cf..b40264523805 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs @@ -48,10 +48,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } + ArgumentNullException.ThrowIfNull(formatter); var message = formatter(state, exception); diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyNavigationManager.cs b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyNavigationManager.cs index c79c8a41e44c..6fedfe37aeb8 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyNavigationManager.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyNavigationManager.cs @@ -52,10 +52,7 @@ public async ValueTask HandleLocationChangingAsync(string uri, string? sta [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(NavigationOptions))] protected override void NavigateToCore(string uri, NavigationOptions options) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); _ = PerformNavigationAsync(); diff --git a/src/Components/WebView/WebView/src/FileExtensionContentTypeProvider.cs b/src/Components/WebView/WebView/src/FileExtensionContentTypeProvider.cs index ecc808df0adf..eff1aa662bf5 100644 --- a/src/Components/WebView/WebView/src/FileExtensionContentTypeProvider.cs +++ b/src/Components/WebView/WebView/src/FileExtensionContentTypeProvider.cs @@ -420,10 +420,7 @@ public FileExtensionContentTypeProvider() /// public FileExtensionContentTypeProvider(IDictionary mapping) { - if (mapping == null) - { - throw new ArgumentNullException(nameof(mapping)); - } + ArgumentNullException.ThrowIfNull(mapping); Mappings = mapping; } diff --git a/src/Components/WebView/WebView/test/Infrastructure/ElementNode.cs b/src/Components/WebView/WebView/test/Infrastructure/ElementNode.cs index 98a6c781fcff..0990659ba58e 100644 --- a/src/Components/WebView/WebView/test/Infrastructure/ElementNode.cs +++ b/src/Components/WebView/WebView/test/Infrastructure/ElementNode.cs @@ -37,15 +37,8 @@ internal void SetAttribute(string key, object value) internal void SetEvent(string eventName, ElementEventDescriptor descriptor) { - if (eventName is null) - { - throw new ArgumentNullException(nameof(eventName)); - } - - if (descriptor is null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(eventName); + ArgumentNullException.ThrowIfNull(descriptor); _events[eventName] = descriptor; } diff --git a/src/Components/WebView/WebView/test/StaticContentProviderTests.cs b/src/Components/WebView/WebView/test/StaticContentProviderTests.cs index 50c234d7a282..24251eb0f77d 100644 --- a/src/Components/WebView/WebView/test/StaticContentProviderTests.cs +++ b/src/Components/WebView/WebView/test/StaticContentProviderTests.cs @@ -45,10 +45,7 @@ private sealed class InMemoryFileProvider : IFileProvider { public InMemoryFileProvider(IDictionary filePathsAndContents) { - if (filePathsAndContents is null) - { - throw new ArgumentNullException(nameof(filePathsAndContents)); - } + ArgumentNullException.ThrowIfNull(filePathsAndContents); FilePathsAndContents = filePathsAndContents; } diff --git a/src/DataProtection/Abstractions/src/DataProtectionCommonExtensions.cs b/src/DataProtection/Abstractions/src/DataProtectionCommonExtensions.cs index 54d0133aed64..779b13116116 100644 --- a/src/DataProtection/Abstractions/src/DataProtectionCommonExtensions.cs +++ b/src/DataProtection/Abstractions/src/DataProtectionCommonExtensions.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.DataProtection.Abstractions; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.DataProtection; @@ -29,15 +30,8 @@ public static class DataProtectionCommonExtensions /// public static IDataProtector CreateProtector(this IDataProtectionProvider provider, IEnumerable purposes) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (purposes == null) - { - throw new ArgumentNullException(nameof(purposes)); - } + ArgumentNullThrowHelper.ThrowIfNull(provider); + ArgumentNullThrowHelper.ThrowIfNull(purposes); bool collectionIsEmpty = true; IDataProtectionProvider retVal = provider; @@ -75,15 +69,8 @@ public static IDataProtector CreateProtector(this IDataProtectionProvider provid /// public static IDataProtector CreateProtector(this IDataProtectionProvider provider, string purpose, params string[] subPurposes) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(provider); + ArgumentNullThrowHelper.ThrowIfNull(purpose); // The method signature isn't simply CreateProtector(this IDataProtectionProvider, params string[] purposes) // because we don't want the code provider.CreateProtector() [parameterless] to inadvertently compile. @@ -105,10 +92,7 @@ public static IDataProtector CreateProtector(this IDataProtectionProvider provid /// If no service exists in . public static IDataProtectionProvider GetDataProtectionProvider(this IServiceProvider services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); // We have our own implementation of GetRequiredService since we don't want to // take a dependency on DependencyInjection.Interfaces. @@ -135,15 +119,8 @@ public static IDataProtectionProvider GetDataProtectionProvider(this IServicePro /// public static IDataProtector GetDataProtector(this IServiceProvider services, IEnumerable purposes) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (purposes == null) - { - throw new ArgumentNullException(nameof(purposes)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(purposes); return services.GetDataProtectionProvider().CreateProtector(purposes); } @@ -164,15 +141,8 @@ public static IDataProtector GetDataProtector(this IServiceProvider services, IE /// public static IDataProtector GetDataProtector(this IServiceProvider services, string purpose, params string[] subPurposes) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(purpose); return services.GetDataProtectionProvider().CreateProtector(purpose, subPurposes); } @@ -185,15 +155,8 @@ public static IDataProtector GetDataProtector(this IServiceProvider services, st /// The protected form of the plaintext data. public static string Protect(this IDataProtector protector, string plaintext) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(plaintext); try { @@ -219,15 +182,8 @@ public static string Protect(this IDataProtector protector, string plaintext) /// public static string Unprotect(this IDataProtector protector, string protectedData) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(protectedData); try { diff --git a/src/DataProtection/Abstractions/src/Microsoft.AspNetCore.DataProtection.Abstractions.csproj b/src/DataProtection/Abstractions/src/Microsoft.AspNetCore.DataProtection.Abstractions.csproj index 0e68ebeb5e76..9c98f96d2db2 100644 --- a/src/DataProtection/Abstractions/src/Microsoft.AspNetCore.DataProtection.Abstractions.csproj +++ b/src/DataProtection/Abstractions/src/Microsoft.AspNetCore.DataProtection.Abstractions.csproj @@ -18,6 +18,9 @@ Microsoft.AspNetCore.DataProtection.IDataProtector + + + diff --git a/src/DataProtection/DataProtection/src/ActivatorExtensions.cs b/src/DataProtection/DataProtection/src/ActivatorExtensions.cs index e8f47ffd6ed1..3ff6ad2c9a47 100644 --- a/src/DataProtection/DataProtection/src/ActivatorExtensions.cs +++ b/src/DataProtection/DataProtection/src/ActivatorExtensions.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.DataProtection; @@ -21,10 +22,7 @@ internal static class ActivatorExtensions public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(this IActivator activator, string implementationTypeName) where T : class { - if (implementationTypeName == null) - { - throw new ArgumentNullException(nameof(implementationTypeName)); - } + ArgumentNullThrowHelper.ThrowIfNull(implementationTypeName); return activator.CreateInstance(typeof(T), implementationTypeName) as T ?? CryptoUtil.Fail("CreateInstance returned null."); diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptor.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptor.cs index ff1002c486c5..1425fa3143ea 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptor.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptor.cs @@ -3,6 +3,7 @@ using System; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -19,15 +20,8 @@ public sealed class AuthenticatedEncryptorDescriptor : IAuthenticatedEncryptorDe /// The master key. public AuthenticatedEncryptorDescriptor(AuthenticatedEncryptorConfiguration configuration, ISecret masterKey) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (masterKey == null) - { - throw new ArgumentNullException(nameof(masterKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(configuration); + ArgumentNullThrowHelper.ThrowIfNull(masterKey); Configuration = configuration; MasterKey = masterKey; diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs index f62c3579327f..f438e8816618 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/AuthenticatedEncryptorDescriptorDeserializer.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -19,10 +20,7 @@ public sealed class AuthenticatedEncryptorDescriptorDeserializer : IAuthenticate /// public IAuthenticatedEncryptorDescriptor ImportFromXml(XElement element) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); // // diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptor.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptor.cs index c91c80a1a2a3..d726bbffdf2a 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptor.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptor.cs @@ -4,6 +4,7 @@ using System; using System.Runtime.Versioning; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -21,15 +22,8 @@ public sealed class CngCbcAuthenticatedEncryptorDescriptor : IAuthenticatedEncry /// The master key. public CngCbcAuthenticatedEncryptorDescriptor(CngCbcAuthenticatedEncryptorConfiguration configuration, ISecret masterKey) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (masterKey == null) - { - throw new ArgumentNullException(nameof(masterKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(configuration); + ArgumentNullThrowHelper.ThrowIfNull(masterKey); Configuration = configuration; MasterKey = masterKey; diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs index 0e17be823a9e..2e43dc84759b 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngCbcAuthenticatedEncryptorDescriptorDeserializer.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -20,10 +21,7 @@ public sealed class CngCbcAuthenticatedEncryptorDescriptorDeserializer : IAuthen /// public IAuthenticatedEncryptorDescriptor ImportFromXml(XElement element) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); // // diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptor.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptor.cs index f1ca729fc2a2..c8c5127cf0cb 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptor.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptor.cs @@ -4,6 +4,7 @@ using System; using System.Runtime.Versioning; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -21,15 +22,8 @@ public sealed class CngGcmAuthenticatedEncryptorDescriptor : IAuthenticatedEncry /// The master key. public CngGcmAuthenticatedEncryptorDescriptor(CngGcmAuthenticatedEncryptorConfiguration configuration, ISecret masterKey) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (masterKey == null) - { - throw new ArgumentNullException(nameof(masterKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(configuration); + ArgumentNullThrowHelper.ThrowIfNull(masterKey); Configuration = configuration; MasterKey = masterKey; diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs index 31887d5c375b..0296a753635b 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/CngGcmAuthenticatedEncryptorDescriptorDeserializer.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -20,10 +21,7 @@ public sealed class CngGcmAuthenticatedEncryptorDescriptorDeserializer : IAuthen /// public IAuthenticatedEncryptorDescriptor ImportFromXml(XElement element) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); // // diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs index 33816cf24867..88e2133d58ac 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptor.cs @@ -4,6 +4,7 @@ using System; using System.Security.Cryptography; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -20,15 +21,8 @@ public sealed class ManagedAuthenticatedEncryptorDescriptor : IAuthenticatedEncr /// The master key. public ManagedAuthenticatedEncryptorDescriptor(ManagedAuthenticatedEncryptorConfiguration configuration, ISecret masterKey) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (masterKey == null) - { - throw new ArgumentNullException(nameof(masterKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(configuration); + ArgumentNullThrowHelper.ThrowIfNull(masterKey); Configuration = configuration; MasterKey = masterKey; diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs index 504b7bb3ad9b..2e8c05e1fb70 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/ManagedAuthenticatedEncryptorDescriptorDeserializer.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -19,10 +20,7 @@ public sealed class ManagedAuthenticatedEncryptorDescriptorDeserializer : IAuthe /// public IAuthenticatedEncryptorDescriptor ImportFromXml(XElement element) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); // // diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlExtensions.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlExtensions.cs index 1cc2a52ae4a6..e87a3eaf3a42 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlExtensions.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -22,10 +23,7 @@ internal static bool IsMarkedAsRequiringEncryption(this XElement element) /// public static void MarkAsRequiresEncryption(this XElement element) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); element.SetAttributeValue(XmlConstants.RequiresEncryptionAttributeName, true); } diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlSerializedDescriptorInfo.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlSerializedDescriptorInfo.cs index 66e1b9d259c3..bae2526a0d14 100644 --- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlSerializedDescriptorInfo.cs +++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/XmlSerializedDescriptorInfo.cs @@ -3,6 +3,7 @@ using System; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; @@ -21,15 +22,8 @@ public sealed class XmlSerializedDescriptorInfo /// method can be used to deserialize . public XmlSerializedDescriptorInfo(XElement serializedDescriptorElement, Type deserializerType) { - if (serializedDescriptorElement == null) - { - throw new ArgumentNullException(nameof(serializedDescriptorElement)); - } - - if (deserializerType == null) - { - throw new ArgumentNullException(nameof(deserializerType)); - } + ArgumentNullThrowHelper.ThrowIfNull(serializedDescriptorElement); + ArgumentNullThrowHelper.ThrowIfNull(deserializerType); if (!typeof(IAuthenticatedEncryptorDescriptorDeserializer).IsAssignableFrom(deserializerType)) { diff --git a/src/DataProtection/DataProtection/src/DataProtectionBuilderExtensions.cs b/src/DataProtection/DataProtection/src/DataProtectionBuilderExtensions.cs index 6f7c39b39f86..13647e67f8cb 100644 --- a/src/DataProtection/DataProtection/src/DataProtectionBuilderExtensions.cs +++ b/src/DataProtection/DataProtection/src/DataProtectionBuilderExtensions.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.DataProtection.XmlEncryption; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; @@ -38,10 +39,7 @@ public static class DataProtectionBuilderExtensions /// public static IDataProtectionBuilder SetApplicationName(this IDataProtectionBuilder builder, string applicationName) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.Configure(options => { @@ -62,15 +60,8 @@ public static IDataProtectionBuilder SetApplicationName(this IDataProtectionBuil /// public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilder builder, IKeyEscrowSink sink) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (sink == null) - { - throw new ArgumentNullException(nameof(sink)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(sink); builder.Services.Configure(options => { @@ -92,10 +83,7 @@ public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilde public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilder builder) where TImplementation : class, IKeyEscrowSink { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.AddSingleton>(services => { @@ -120,15 +108,8 @@ public static IDataProtectionBuilder AddKeyEscrowSink(this IDat /// public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilder builder, Func factory) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(factory); builder.Services.AddSingleton>(services => { @@ -150,15 +131,8 @@ public static IDataProtectionBuilder AddKeyEscrowSink(this IDataProtectionBuilde /// A reference to the after this operation has completed. public static IDataProtectionBuilder AddKeyManagementOptions(this IDataProtectionBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -175,10 +149,7 @@ public static IDataProtectionBuilder AddKeyManagementOptions(this IDataProtectio /// public static IDataProtectionBuilder DisableAutomaticKeyGeneration(this IDataProtectionBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.Configure(options => { @@ -196,15 +167,8 @@ public static IDataProtectionBuilder DisableAutomaticKeyGeneration(this IDataPro /// A reference to the after this operation has completed. public static IDataProtectionBuilder PersistKeysToFileSystem(this IDataProtectionBuilder builder, DirectoryInfo directory) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (directory == null) - { - throw new ArgumentNullException(nameof(directory)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(directory); builder.Services.AddSingleton>(services => { @@ -227,15 +191,8 @@ public static IDataProtectionBuilder PersistKeysToFileSystem(this IDataProtectio [SupportedOSPlatform("windows")] public static IDataProtectionBuilder PersistKeysToRegistry(this IDataProtectionBuilder builder, RegistryKey registryKey) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (registryKey == null) - { - throw new ArgumentNullException(nameof(registryKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(registryKey); builder.Services.AddSingleton>(services => { @@ -257,15 +214,8 @@ public static IDataProtectionBuilder PersistKeysToRegistry(this IDataProtectionB /// A reference to the after this operation has completed. public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtectionBuilder builder, X509Certificate2 certificate) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(certificate); builder.Services.AddSingleton>(services => { @@ -289,15 +239,8 @@ public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtec /// A reference to the after this operation has completed. public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtectionBuilder builder, string thumbprint) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (thumbprint == null) - { - throw new ArgumentNullException(nameof(thumbprint)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(thumbprint); // Make sure the thumbprint corresponds to a valid certificate. if (new CertificateResolver().ResolveCertificate(thumbprint) == null) @@ -330,10 +273,7 @@ public static IDataProtectionBuilder ProtectKeysWithCertificate(this IDataProtec /// A reference to the after this operation has completed. public static IDataProtectionBuilder UnprotectKeysWithAnyCertificate(this IDataProtectionBuilder builder, params X509Certificate2[] certificates) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.Configure(o => { @@ -361,10 +301,7 @@ public static IDataProtectionBuilder UnprotectKeysWithAnyCertificate(this IDataP [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); return builder.ProtectKeysWithDpapi(protectToLocalMachine: false); } @@ -384,10 +321,7 @@ public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBu [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder, bool protectToLocalMachine) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.AddSingleton>(services => { @@ -415,10 +349,7 @@ public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBu [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); return builder.ProtectKeysWithDpapiNG( protectionDescriptorRule: DpapiNGXmlEncryptor.GetDefaultProtectionDescriptorString(), @@ -443,15 +374,8 @@ public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtection [SupportedOSPlatform("windows")] public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder, string protectionDescriptorRule, DpapiNGProtectionDescriptorFlags flags) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (protectionDescriptorRule == null) - { - throw new ArgumentNullException(nameof(protectionDescriptorRule)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(protectionDescriptorRule); builder.Services.AddSingleton>(services => { @@ -476,10 +400,7 @@ public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtection /// A reference to the after this operation has completed. public static IDataProtectionBuilder SetDefaultKeyLifetime(this IDataProtectionBuilder builder, TimeSpan lifetime) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); if (lifetime < TimeSpan.Zero) { @@ -503,15 +424,8 @@ public static IDataProtectionBuilder SetDefaultKeyLifetime(this IDataProtectionB /// A reference to the after this operation has completed. public static IDataProtectionBuilder UseCryptographicAlgorithms(this IDataProtectionBuilder builder, AuthenticatedEncryptorConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(configuration); return UseCryptographicAlgorithmsCore(builder, configuration); } @@ -532,15 +446,8 @@ public static IDataProtectionBuilder UseCryptographicAlgorithms(this IDataProtec [SupportedOSPlatform("windows")] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, CngCbcAuthenticatedEncryptorConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(configuration); return UseCryptographicAlgorithmsCore(builder, configuration); } @@ -561,15 +468,8 @@ public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IData [SupportedOSPlatform("windows")] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, CngGcmAuthenticatedEncryptorConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(configuration); return UseCryptographicAlgorithmsCore(builder, configuration); } @@ -586,15 +486,8 @@ public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IData [EditorBrowsable(EditorBrowsableState.Advanced)] public static IDataProtectionBuilder UseCustomCryptographicAlgorithms(this IDataProtectionBuilder builder, ManagedAuthenticatedEncryptorConfiguration configuration) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(configuration); return UseCryptographicAlgorithmsCore(builder, configuration); } @@ -623,10 +516,7 @@ private static IDataProtectionBuilder UseCryptographicAlgorithmsCore(IDataProtec /// public static IDataProtectionBuilder UseEphemeralDataProtectionProvider(this IDataProtectionBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); builder.Services.Replace(ServiceDescriptor.Singleton()); diff --git a/src/DataProtection/DataProtection/src/DataProtectionServiceCollectionExtensions.cs b/src/DataProtection/DataProtection/src/DataProtectionServiceCollectionExtensions.cs index 7965b0bf6269..9a63abe0e1c3 100644 --- a/src/DataProtection/DataProtection/src/DataProtectionServiceCollectionExtensions.cs +++ b/src/DataProtection/DataProtection/src/DataProtectionServiceCollectionExtensions.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; using Microsoft.AspNetCore.DataProtection.XmlEncryption; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -30,10 +31,7 @@ public static class DataProtectionServiceCollectionExtensions /// The to add services to. public static IDataProtectionBuilder AddDataProtection(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); services.TryAddSingleton(); services.AddOptions(); @@ -50,15 +48,8 @@ public static IDataProtectionBuilder AddDataProtection(this IServiceCollection s /// A reference to this instance after the operation has completed. public static IDataProtectionBuilder AddDataProtection(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); var builder = services.AddDataProtection(); services.Configure(setupAction); diff --git a/src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs b/src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs index 05d8ce815a27..1c2c2c2fa835 100644 --- a/src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs +++ b/src/DataProtection/DataProtection/src/EphemeralDataProtectionProvider.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -40,10 +41,7 @@ public EphemeralDataProtectionProvider() /// The . public EphemeralDataProtectionProvider(ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullThrowHelper.ThrowIfNull(loggerFactory); IKeyRingProvider keyringProvider; if (OSVersionUtil.IsWindows()) @@ -68,10 +66,7 @@ public EphemeralDataProtectionProvider(ILoggerFactory loggerFactory) /// public IDataProtector CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); // just forward to the underlying provider return _dataProtectionProvider.CreateProtector(purpose); diff --git a/src/DataProtection/DataProtection/src/Internal/DataProtectionBuilder.cs b/src/DataProtection/DataProtection/src/Internal/DataProtectionBuilder.cs index baa3bd6cbb75..e914c5e948a3 100644 --- a/src/DataProtection/DataProtection/src/Internal/DataProtectionBuilder.cs +++ b/src/DataProtection/DataProtection/src/Internal/DataProtectionBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.DataProtection.Internal; @@ -16,10 +17,7 @@ internal sealed class DataProtectionBuilder : IDataProtectionBuilder /// public DataProtectionBuilder(IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); Services = services; } diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs index fb8eb11becff..dd28c84db68d 100644 --- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs +++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.KeyManagement; @@ -20,10 +21,7 @@ public KeyRingBasedDataProtectionProvider(IKeyRingProvider keyRingProvider, ILog public IDataProtector CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); return new KeyRingBasedDataProtector( logger: _logger, diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs index 55d0bae2d7fb..ed0e20cdd6cd 100644 --- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs +++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.KeyManagement.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.KeyManagement; @@ -58,10 +59,7 @@ private static string[] ConcatPurposes(string[]? originalPurposes, string newPur public IDataProtector CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); return new KeyRingBasedDataProtector( logger: _logger, @@ -79,10 +77,7 @@ private static string JoinPurposesForLog(IEnumerable purposes) public byte[] DangerousUnprotect(byte[] protectedData, bool ignoreRevocationErrors, out bool requiresMigration, out bool wasRevoked) { // argument & state checking - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); UnprotectStatus status; var retVal = UnprotectCore(protectedData, ignoreRevocationErrors, status: out status); @@ -93,10 +88,7 @@ public byte[] DangerousUnprotect(byte[] protectedData, bool ignoreRevocationErro public byte[] Protect(byte[] plaintext) { - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintext); try { @@ -182,10 +174,7 @@ private static bool TryGetVersionFromMagicHeader(uint magicHeader, out int versi public byte[] Unprotect(byte[] protectedData) { - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); // Argument checking will be done by the callee return DangerousUnprotect(protectedData, diff --git a/src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj b/src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj index 06f353ceb906..5818326c4ef1 100644 --- a/src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj +++ b/src/DataProtection/DataProtection/src/Microsoft.AspNetCore.DataProtection.csproj @@ -20,6 +20,8 @@ Condition="'$(TargetFramework)' != '$(DefaultNetCoreTargetFramework)'" /> + + diff --git a/src/DataProtection/DataProtection/src/Repositories/EphemeralXmlRepository.cs b/src/DataProtection/DataProtection/src/Repositories/EphemeralXmlRepository.cs index 13bd29230cbb..9d0d0eb65075 100644 --- a/src/DataProtection/DataProtection/src/Repositories/EphemeralXmlRepository.cs +++ b/src/DataProtection/DataProtection/src/Repositories/EphemeralXmlRepository.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.Repositories; @@ -43,10 +44,7 @@ private IEnumerable GetAllElementsCore() public void StoreElement(XElement element, string friendlyName) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); var cloned = new XElement(element); // makes a deep copy so caller doesn't inadvertently modify it diff --git a/src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs b/src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs index 7520bf1562b0..d80ec7d44543 100644 --- a/src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs +++ b/src/DataProtection/DataProtection/src/Repositories/FileSystemXmlRepository.cs @@ -8,6 +8,7 @@ using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.AspNetCore.DataProtection.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.Repositories; @@ -110,10 +111,7 @@ private XElement ReadElementFromFile(string fullPath) /// public virtual void StoreElement(XElement element, string friendlyName) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); if (!IsSafeFilename(friendlyName)) { diff --git a/src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs b/src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs index 836ec5a1ce3d..c1fa11b7fbe4 100644 --- a/src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs +++ b/src/DataProtection/DataProtection/src/Repositories/RegistryXmlRepository.cs @@ -8,6 +8,7 @@ using System.Runtime.Versioning; using System.Security.Principal; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Win32; @@ -30,10 +31,7 @@ public class RegistryXmlRepository : IXmlRepository /// The . public RegistryXmlRepository(RegistryKey registryKey, ILoggerFactory loggerFactory) { - if (registryKey == null) - { - throw new ArgumentNullException(nameof(registryKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(registryKey); RegistryKey = registryKey; _logger = loggerFactory.CreateLogger(); @@ -137,10 +135,7 @@ private static bool IsSafeRegistryValueName(string filename) /// public virtual void StoreElement(XElement element, string friendlyName) { - if (element == null) - { - throw new ArgumentNullException(nameof(element)); - } + ArgumentNullThrowHelper.ThrowIfNull(element); if (!IsSafeRegistryValueName(friendlyName)) { diff --git a/src/DataProtection/DataProtection/src/Secret.cs b/src/DataProtection/DataProtection/src/Secret.cs index 755ada3dd0e7..1077b315f0c3 100644 --- a/src/DataProtection/DataProtection/src/Secret.cs +++ b/src/DataProtection/DataProtection/src/Secret.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Cryptography.Cng; using Microsoft.AspNetCore.Cryptography.SafeHandles; using Microsoft.AspNetCore.DataProtection.Managed; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection; @@ -39,10 +40,7 @@ public Secret(ArraySegment value) public Secret(byte[] value) : this(new ArraySegment(value)) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); } /// @@ -69,10 +67,7 @@ public Secret(byte* secret, int secretLength) /// public Secret(ISecret secret) { - if (secret == null) - { - throw new ArgumentNullException(nameof(secret)); - } + ArgumentNullThrowHelper.ThrowIfNull(secret); var other = secret as Secret; if (other != null) diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs b/src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs index e49015e772c9..11009b35f1e5 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/CertificateResolver.cs @@ -4,6 +4,7 @@ using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -20,10 +21,7 @@ public class CertificateResolver : ICertificateResolver /// The resolved , or null if the certificate cannot be found. public virtual X509Certificate2? ResolveCertificate(string thumbprint) { - if (thumbprint == null) - { - throw new ArgumentNullException(nameof(thumbprint)); - } + ArgumentNullThrowHelper.ThrowIfNull(thumbprint); if (String.IsNullOrEmpty(thumbprint)) { diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs index 2a420be490e4..91f72d35306d 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/CertificateXmlEncryptor.cs @@ -7,6 +7,7 @@ using System.Xml; using System.Xml.Linq; using Microsoft.AspNetCore.Cryptography; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -28,15 +29,8 @@ public sealed class CertificateXmlEncryptor : IInternalCertificateXmlEncryptor, public CertificateXmlEncryptor(string thumbprint, ICertificateResolver certificateResolver, ILoggerFactory loggerFactory) : this(loggerFactory, encryptor: null) { - if (thumbprint == null) - { - throw new ArgumentNullException(nameof(thumbprint)); - } - - if (certificateResolver == null) - { - throw new ArgumentNullException(nameof(certificateResolver)); - } + ArgumentNullThrowHelper.ThrowIfNull(thumbprint); + ArgumentNullThrowHelper.ThrowIfNull(certificateResolver); _certFactory = CreateCertFactory(thumbprint, certificateResolver); } @@ -48,10 +42,7 @@ public CertificateXmlEncryptor(string thumbprint, ICertificateResolver certifica public CertificateXmlEncryptor(X509Certificate2 certificate, ILoggerFactory loggerFactory) : this(loggerFactory, encryptor: null) { - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullThrowHelper.ThrowIfNull(certificate); _certFactory = () => certificate; } @@ -74,10 +65,7 @@ internal CertificateXmlEncryptor(ILoggerFactory loggerFactory, IInternalCertific /// public EncryptedXmlInfo Encrypt(XElement plaintextElement) { - if (plaintextElement == null) - { - throw new ArgumentNullException(nameof(plaintextElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintextElement); // // ... diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs index 55c84bbedf0c..363218042514 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlDecryptor.cs @@ -5,6 +5,7 @@ using System.Xml.Linq; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.Cng; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -45,10 +46,7 @@ public DpapiNGXmlDecryptor(IServiceProvider? services) /// The decrypted form of . public XElement Decrypt(XElement encryptedElement) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(encryptedElement); try { diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs index a5e7cc92aea2..bcb3379800be 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiNGXmlEncryptor.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.Cryptography.SafeHandles; using Microsoft.AspNetCore.DataProtection.Cng; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -33,10 +34,7 @@ public sealed class DpapiNGXmlEncryptor : IXmlEncryptor /// The . public DpapiNGXmlEncryptor(string protectionDescriptorRule, DpapiNGProtectionDescriptorFlags flags, ILoggerFactory loggerFactory) { - if (protectionDescriptorRule == null) - { - throw new ArgumentNullException(nameof(protectionDescriptorRule)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectionDescriptorRule); CryptoUtil.AssertPlatformIsWindows8OrLater(); @@ -58,10 +56,7 @@ public DpapiNGXmlEncryptor(string protectionDescriptorRule, DpapiNGProtectionDes /// public EncryptedXmlInfo Encrypt(XElement plaintextElement) { - if (plaintextElement == null) - { - throw new ArgumentNullException(nameof(plaintextElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintextElement); var protectionDescriptorRuleString = _protectionDescriptorHandle.GetProtectionDescriptorRuleString(); _logger.EncryptingToWindowsDPAPINGUsingProtectionDescriptorRule(protectionDescriptorRuleString); diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs index fa9f4fb01edb..d3655f04ab87 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlDecryptor.cs @@ -5,6 +5,7 @@ using System.Xml.Linq; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.Cng; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -42,10 +43,7 @@ public DpapiXmlDecryptor(IServiceProvider? services) /// The decrypted form of . public XElement Decrypt(XElement encryptedElement) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(encryptedElement); _logger.DecryptingSecretElementUsingWindowsDPAPI(); diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlEncryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlEncryptor.cs index 4d4f914cfffb..4d9ab81917f8 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlEncryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/DpapiXmlEncryptor.cs @@ -7,6 +7,7 @@ using System.Xml.Linq; using Microsoft.AspNetCore.Cryptography; using Microsoft.AspNetCore.DataProtection.Cng; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -48,10 +49,7 @@ public DpapiXmlEncryptor(bool protectToLocalMachine, ILoggerFactory loggerFactor /// public EncryptedXmlInfo Encrypt(XElement plaintextElement) { - if (plaintextElement == null) - { - throw new ArgumentNullException(nameof(plaintextElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintextElement); if (_protectToLocalMachine) { _logger.EncryptingToWindowsDPAPIForLocalMachineAccount(); diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs index 3357ef057ce6..1598241cac3e 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlDecryptor.cs @@ -6,6 +6,7 @@ using System.Security.Cryptography.Xml; using System.Xml; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -44,10 +45,7 @@ public EncryptedXmlDecryptor(IServiceProvider? services) /// The decrypted form of . public XElement Decrypt(XElement encryptedElement) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(encryptedElement); // // ... diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlInfo.cs b/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlInfo.cs index 90c3d8d7d0af..b26bc9f7e79f 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlInfo.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/EncryptedXmlInfo.cs @@ -3,6 +3,7 @@ using System; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -20,15 +21,8 @@ public sealed class EncryptedXmlInfo /// method can be used to decrypt . public EncryptedXmlInfo(XElement encryptedElement, Type decryptorType) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } - - if (decryptorType == null) - { - throw new ArgumentNullException(nameof(decryptorType)); - } + ArgumentNullThrowHelper.ThrowIfNull(encryptedElement); + ArgumentNullThrowHelper.ThrowIfNull(decryptorType); if (!typeof(IXmlDecryptor).IsAssignableFrom(decryptorType)) { diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlDecryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlDecryptor.cs index 35e98384203a..51a3e7990060 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlDecryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlDecryptor.cs @@ -4,6 +4,7 @@ using System; using System.Linq; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -19,10 +20,7 @@ public sealed class NullXmlDecryptor : IXmlDecryptor /// The decrypted form of . public XElement Decrypt(XElement encryptedElement) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(encryptedElement); // // diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs b/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs index 8debbcd9161d..749c6c0e50d2 100644 --- a/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs +++ b/src/DataProtection/DataProtection/src/XmlEncryption/NullXmlEncryptor.cs @@ -3,6 +3,7 @@ using System; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.DataProtection.XmlEncryption; @@ -43,10 +44,7 @@ public NullXmlEncryptor(IServiceProvider? services) /// public EncryptedXmlInfo Encrypt(XElement plaintextElement) { - if (plaintextElement == null) - { - throw new ArgumentNullException(nameof(plaintextElement)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintextElement); _logger.EncryptingUsingNullEncryptor(); diff --git a/src/DataProtection/EntityFrameworkCore/src/EntityFrameworkCoreXmlRepository.cs b/src/DataProtection/EntityFrameworkCore/src/EntityFrameworkCoreXmlRepository.cs index 8646adf44014..b1d206da0352 100644 --- a/src/DataProtection/EntityFrameworkCore/src/EntityFrameworkCoreXmlRepository.cs +++ b/src/DataProtection/EntityFrameworkCore/src/EntityFrameworkCoreXmlRepository.cs @@ -31,10 +31,7 @@ public class EntityFrameworkCoreXmlRepository : IXmlRepository [DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(DataProtectionKey))] public EntityFrameworkCoreXmlRepository(IServiceProvider services, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger>(); _services = services ?? throw new ArgumentNullException(nameof(services)); diff --git a/src/DataProtection/samples/CustomEncryptorSample/CustomXmlDecryptor.cs b/src/DataProtection/samples/CustomEncryptorSample/CustomXmlDecryptor.cs index d67e50693ab1..d0b73966f2d7 100644 --- a/src/DataProtection/samples/CustomEncryptorSample/CustomXmlDecryptor.cs +++ b/src/DataProtection/samples/CustomEncryptorSample/CustomXmlDecryptor.cs @@ -19,10 +19,7 @@ public CustomXmlDecryptor(IServiceProvider services) public XElement Decrypt(XElement encryptedElement) { - if (encryptedElement == null) - { - throw new ArgumentNullException(nameof(encryptedElement)); - } + ArgumentNullException.ThrowIfNull(encryptedElement); return new XElement(encryptedElement.Elements().Single()); } diff --git a/src/DataProtection/samples/CustomEncryptorSample/CustomXmlEncryptor.cs b/src/DataProtection/samples/CustomEncryptorSample/CustomXmlEncryptor.cs index 874cd6214864..3da66e939a08 100644 --- a/src/DataProtection/samples/CustomEncryptorSample/CustomXmlEncryptor.cs +++ b/src/DataProtection/samples/CustomEncryptorSample/CustomXmlEncryptor.cs @@ -19,10 +19,7 @@ public CustomXmlEncryptor(IServiceProvider services) public EncryptedXmlInfo Encrypt(XElement plaintextElement) { - if (plaintextElement == null) - { - throw new ArgumentNullException(nameof(plaintextElement)); - } + ArgumentNullException.ThrowIfNull(plaintextElement); _logger.LogInformation("Not encrypting key"); diff --git a/src/DefaultBuilder/src/ConfigureHostBuilder.cs b/src/DefaultBuilder/src/ConfigureHostBuilder.cs index 423efee0c7de..d796d1e739b1 100644 --- a/src/DefaultBuilder/src/ConfigureHostBuilder.cs +++ b/src/DefaultBuilder/src/ConfigureHostBuilder.cs @@ -51,10 +51,7 @@ public IHostBuilder ConfigureAppConfiguration(Action public IHostBuilder ConfigureContainer(Action configureDelegate) { - if (configureDelegate is null) - { - throw new ArgumentNullException(nameof(configureDelegate)); - } + ArgumentNullException.ThrowIfNull(configureDelegate); _configureContainerActions.Add((context, containerBuilder) => configureDelegate(context, (TContainerBuilder)containerBuilder)); @@ -105,10 +102,7 @@ public IHostBuilder ConfigureServices(Action public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) where TContainerBuilder : notnull { - if (factory is null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); _serviceProviderFactory = new ServiceProviderFactoryAdapter(factory); return this; diff --git a/src/DefaultBuilder/src/GenericHostBuilderExtensions.cs b/src/DefaultBuilder/src/GenericHostBuilderExtensions.cs index a3ef5aa033bc..f61d482b4066 100644 --- a/src/DefaultBuilder/src/GenericHostBuilderExtensions.cs +++ b/src/DefaultBuilder/src/GenericHostBuilderExtensions.cs @@ -31,10 +31,7 @@ public static class GenericHostBuilderExtensions /// A reference to the after the operation has completed. public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action configure) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); return builder.ConfigureWebHostDefaults(configure, _ => { }); } @@ -60,10 +57,7 @@ public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, A /// A reference to the after the operation has completed. public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action configure, Action configureOptions) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); return builder.ConfigureWebHost(webHostBuilder => { diff --git a/src/Extensions/Features/src/FeatureCollection.cs b/src/Extensions/Features/src/FeatureCollection.cs index 29dc500eb48c..db39033b41aa 100644 --- a/src/Extensions/Features/src/FeatureCollection.cs +++ b/src/Extensions/Features/src/FeatureCollection.cs @@ -5,6 +5,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Http.Features; @@ -33,10 +34,7 @@ public FeatureCollection() /// is less than 0 public FeatureCollection(int initialCapacity) { - if (initialCapacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(initialCapacity)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(initialCapacity); _initialCapacity = initialCapacity; } @@ -64,19 +62,13 @@ public object? this[Type key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); return _features != null && _features.TryGetValue(key, out var result) ? result : _defaults?[key]; } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); if (value == null) { diff --git a/src/Extensions/Features/src/FeatureCollectionExtensions.cs b/src/Extensions/Features/src/FeatureCollectionExtensions.cs index 62c8e9b67a6f..a6cefbdde510 100644 --- a/src/Extensions/Features/src/FeatureCollectionExtensions.cs +++ b/src/Extensions/Features/src/FeatureCollectionExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Http.Features; @@ -20,10 +21,7 @@ public static class FeatureCollectionExtensions public static TFeature GetRequiredFeature(this IFeatureCollection featureCollection) where TFeature : notnull { - if (featureCollection is null) - { - throw new ArgumentNullException(nameof(featureCollection)); - } + ArgumentNullThrowHelper.ThrowIfNull(featureCollection); return featureCollection.Get() ?? throw new InvalidOperationException($"Feature '{typeof(TFeature)}' is not present."); } @@ -37,15 +35,8 @@ public static TFeature GetRequiredFeature(this IFeatureCollection feat /// The requested feature. public static object GetRequiredFeature(this IFeatureCollection featureCollection, Type key) { - if (featureCollection is null) - { - throw new ArgumentNullException(nameof(featureCollection)); - } - - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(featureCollection); + ArgumentNullThrowHelper.ThrowIfNull(key); return featureCollection[key] ?? throw new InvalidOperationException($"Feature '{key}' is not present."); } diff --git a/src/Extensions/Features/src/Microsoft.Extensions.Features.csproj b/src/Extensions/Features/src/Microsoft.Extensions.Features.csproj index b3295cf886eb..e995b666bd63 100644 --- a/src/Extensions/Features/src/Microsoft.Extensions.Features.csproj +++ b/src/Extensions/Features/src/Microsoft.Extensions.Features.csproj @@ -15,4 +15,10 @@ Microsoft.AspNetCore.Http.Features.FeatureCollection true + + + + + + diff --git a/src/Features/JsonPatch/src/Microsoft.AspNetCore.JsonPatch.csproj b/src/Features/JsonPatch/src/Microsoft.AspNetCore.JsonPatch.csproj index 8218db1c7202..6c78abd09dbd 100644 --- a/src/Features/JsonPatch/src/Microsoft.AspNetCore.JsonPatch.csproj +++ b/src/Features/JsonPatch/src/Microsoft.AspNetCore.JsonPatch.csproj @@ -4,6 +4,7 @@ ASP.NET Core support for JSON PATCH. $(DefaultNetCoreTargetFramework);$(DefaultNetFxTargetFramework);netstandard2.0 $(NoWarn);CS1591 + $(DefineConstants);INTERNAL_NULLABLE_ATTRIBUTES true aspnetcore;json;jsonpatch disable @@ -11,6 +12,12 @@ + + + + + + diff --git a/src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs b/src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs index baeb308f9f51..3ebb3077cb6a 100644 --- a/src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs +++ b/src/Features/JsonPatch/test/IntegrationTests/NestedObjectIntegrationTest.cs @@ -3,6 +3,7 @@ using System; using System.Dynamic; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json; using Xunit; @@ -342,10 +343,7 @@ public string StringProperty set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); stringProperty = value; } diff --git a/src/Framework/App.Ref/src/CompatibilitySuppressions.xml b/src/Framework/App.Ref/src/CompatibilitySuppressions.xml index 2d1a36843ca4..053fd4d1b580 100644 --- a/src/Framework/App.Ref/src/CompatibilitySuppressions.xml +++ b/src/Framework/App.Ref/src/CompatibilitySuppressions.xml @@ -1,5 +1,6 @@  - + + PKV004 net7.0 diff --git a/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml b/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml index 5beb41b8eec0..36fe412dc72d 100644 --- a/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml +++ b/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml @@ -1,5 +1,6 @@  - + + PKV0001 net7.0 diff --git a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/GrpcJsonTranscodingServiceExtensions.cs b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/GrpcJsonTranscodingServiceExtensions.cs index 6a65420cac31..0fcf66905d37 100644 --- a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/GrpcJsonTranscodingServiceExtensions.cs +++ b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/GrpcJsonTranscodingServiceExtensions.cs @@ -23,10 +23,7 @@ public static class GrpcJsonTranscodingServiceExtensions /// The same instance of the for chaining. public static IGrpcServerBuilder AddJsonTranscoding(this IGrpcServerBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IServiceMethodProvider<>), typeof(JsonTranscodingServiceMethodProvider<>))); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, GrpcJsonTranscodingOptionsSetup>()); @@ -43,10 +40,7 @@ public static IGrpcServerBuilder AddJsonTranscoding(this IGrpcServerBuilder buil /// The same instance of the for chaining. public static IGrpcServerBuilder AddJsonTranscoding(this IGrpcServerBuilder builder, Action configureOptions) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(configureOptions); @@ -64,10 +58,7 @@ public GrpcJsonTranscodingOptionsSetup(DescriptorRegistry descriptorRegistry) public void Configure(GrpcJsonTranscodingOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.DescriptorRegistry = _descriptorRegistry; } diff --git a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/HttpContextStreamWriter.cs b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/HttpContextStreamWriter.cs index baa30ad7a6ce..a688aab092a9 100644 --- a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/HttpContextStreamWriter.cs +++ b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/HttpContextStreamWriter.cs @@ -41,10 +41,7 @@ public Task WriteAsync(TResponse message) private async Task WriteAsyncCore(TResponse message, CancellationToken cancellationToken) { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(message); // Register cancellation token early to ensure request is canceled if cancellation is requested. CancellationTokenRegistration? registration = null; diff --git a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/JsonRequestHelpers.cs b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/JsonRequestHelpers.cs index fe97e61c20d6..9ed3180a06ae 100644 --- a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/JsonRequestHelpers.cs +++ b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.JsonTranscoding/Internal/JsonRequestHelpers.cs @@ -25,10 +25,7 @@ internal static class JsonRequestHelpers public static bool HasJsonContentType(HttpRequest request, out StringSegment charset) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mt)) { diff --git a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.Swagger/GrpcSwaggerServiceExtensions.cs b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.Swagger/GrpcSwaggerServiceExtensions.cs index 71eeb1854834..8fa484bd770f 100644 --- a/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.Swagger/GrpcSwaggerServiceExtensions.cs +++ b/src/Grpc/JsonTranscoding/src/Microsoft.AspNetCore.Grpc.Swagger/GrpcSwaggerServiceExtensions.cs @@ -25,10 +25,7 @@ public static class GrpcSwaggerServiceExtensions /// The so that additional calls can be chained. public static IServiceCollection AddGrpcSwagger(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddGrpc().AddJsonTranscoding(); diff --git a/src/HealthChecks/HealthChecks/src/Microsoft.Extensions.Diagnostics.HealthChecks.csproj b/src/HealthChecks/HealthChecks/src/Microsoft.Extensions.Diagnostics.HealthChecks.csproj index 0bd7265565ce..dec758bfac7b 100644 --- a/src/HealthChecks/HealthChecks/src/Microsoft.Extensions.Diagnostics.HealthChecks.csproj +++ b/src/HealthChecks/HealthChecks/src/Microsoft.Extensions.Diagnostics.HealthChecks.csproj @@ -24,6 +24,8 @@ Microsoft.Extensions.Diagnostics.HealthChecks.IHealthChecksBuilder + + diff --git a/src/Hosting/Abstractions/src/HostingAbstractionsWebHostBuilderExtensions.cs b/src/Hosting/Abstractions/src/HostingAbstractionsWebHostBuilderExtensions.cs index 9e62c04c38fe..930fde23ac41 100644 --- a/src/Hosting/Abstractions/src/HostingAbstractionsWebHostBuilderExtensions.cs +++ b/src/Hosting/Abstractions/src/HostingAbstractionsWebHostBuilderExtensions.cs @@ -52,10 +52,7 @@ public static IWebHostBuilder CaptureStartupErrors(this IWebHostBuilder hostBuil [RequiresUnreferencedCode("This API searches the specified assembly for a startup type using reflection. The startup type may be trimmed. Please use UseStartup() to specify the startup type explicitly.")] public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, string startupAssemblyName) { - if (startupAssemblyName == null) - { - throw new ArgumentNullException(nameof(startupAssemblyName)); - } + ArgumentNullException.ThrowIfNull(startupAssemblyName); return hostBuilder .UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName) @@ -70,10 +67,7 @@ public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, strin /// The . public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, IServer server) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } + ArgumentNullException.ThrowIfNull(server); return hostBuilder.ConfigureServices(services => { @@ -91,10 +85,7 @@ public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, IServe /// The . public static IWebHostBuilder UseEnvironment(this IWebHostBuilder hostBuilder, string environment) { - if (environment == null) - { - throw new ArgumentNullException(nameof(environment)); - } + ArgumentNullException.ThrowIfNull(environment); return hostBuilder.UseSetting(WebHostDefaults.EnvironmentKey, environment); } @@ -107,10 +98,7 @@ public static IWebHostBuilder UseEnvironment(this IWebHostBuilder hostBuilder, s /// The . public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot) { - if (contentRoot == null) - { - throw new ArgumentNullException(nameof(contentRoot)); - } + ArgumentNullException.ThrowIfNull(contentRoot); return hostBuilder.UseSetting(WebHostDefaults.ContentRootKey, contentRoot); } @@ -123,10 +111,7 @@ public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, s /// The . public static IWebHostBuilder UseWebRoot(this IWebHostBuilder hostBuilder, string webRoot) { - if (webRoot == null) - { - throw new ArgumentNullException(nameof(webRoot)); - } + ArgumentNullException.ThrowIfNull(webRoot); return hostBuilder.UseSetting(WebHostDefaults.WebRootKey, webRoot); } @@ -139,10 +124,7 @@ public static IWebHostBuilder UseWebRoot(this IWebHostBuilder hostBuilder, strin /// The . public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, [StringSyntax(StringSyntaxAttribute.Uri)] params string[] urls) { - if (urls == null) - { - throw new ArgumentNullException(nameof(urls)); - } + ArgumentNullException.ThrowIfNull(urls); return hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Join(';', urls)); } diff --git a/src/Hosting/Abstractions/src/HostingEnvironmentExtensions.cs b/src/Hosting/Abstractions/src/HostingEnvironmentExtensions.cs index ccdaced3171d..ce3ba45c5bb6 100644 --- a/src/Hosting/Abstractions/src/HostingEnvironmentExtensions.cs +++ b/src/Hosting/Abstractions/src/HostingEnvironmentExtensions.cs @@ -16,10 +16,7 @@ public static class HostingEnvironmentExtensions /// True if the environment name is , otherwise false. public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } @@ -31,10 +28,7 @@ public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) /// True if the environment name is , otherwise false. public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } @@ -46,10 +40,7 @@ public static bool IsStaging(this IHostingEnvironment hostingEnvironment) /// True if the environment name is , otherwise false. public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } @@ -64,10 +55,7 @@ public static bool IsEnvironment( this IHostingEnvironment hostingEnvironment, string environmentName) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); return string.Equals( hostingEnvironment.EnvironmentName, diff --git a/src/Hosting/Abstractions/src/HostingStartupAttribute.cs b/src/Hosting/Abstractions/src/HostingStartupAttribute.cs index 9d7e9e90ff84..f08aa819c81d 100644 --- a/src/Hosting/Abstractions/src/HostingStartupAttribute.cs +++ b/src/Hosting/Abstractions/src/HostingStartupAttribute.cs @@ -17,10 +17,7 @@ public sealed class HostingStartupAttribute : Attribute /// A type that implements . public HostingStartupAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type hostingStartupType) { - if (hostingStartupType == null) - { - throw new ArgumentNullException(nameof(hostingStartupType)); - } + ArgumentNullException.ThrowIfNull(hostingStartupType); if (!typeof(IHostingStartup).IsAssignableFrom(hostingStartupType)) { diff --git a/src/Hosting/Hosting/src/GenericHostWebHostBuilderExtensions.cs b/src/Hosting/Hosting/src/GenericHostWebHostBuilderExtensions.cs index e1293e8cf93b..7bd6f86a49af 100644 --- a/src/Hosting/Hosting/src/GenericHostWebHostBuilderExtensions.cs +++ b/src/Hosting/Hosting/src/GenericHostWebHostBuilderExtensions.cs @@ -20,10 +20,7 @@ public static class GenericHostWebHostBuilderExtensions /// The . public static IHostBuilder ConfigureWebHost(this IHostBuilder builder, Action configure) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); return builder.ConfigureWebHost(configure, _ => { }); } @@ -37,15 +34,8 @@ public static IHostBuilder ConfigureWebHost(this IHostBuilder builder, ActionThe . public static IHostBuilder ConfigureWebHost(this IHostBuilder builder, Action configure, Action configureWebHostBuilder) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } - - if (configureWebHostBuilder is null) - { - throw new ArgumentNullException(nameof(configureWebHostBuilder)); - } + ArgumentNullException.ThrowIfNull(configure); + ArgumentNullException.ThrowIfNull(configureWebHostBuilder); // Light up custom implementations namely ConfigureHostBuilder which throws. if (builder is ISupportsConfigureWebHost supportsConfigureWebHost) diff --git a/src/Hosting/Hosting/src/Http/DefaultHttpContextFactory.cs b/src/Hosting/Hosting/src/Http/DefaultHttpContextFactory.cs index 7460645339dc..a5b6541b0f91 100644 --- a/src/Hosting/Hosting/src/Http/DefaultHttpContextFactory.cs +++ b/src/Hosting/Hosting/src/Http/DefaultHttpContextFactory.cs @@ -43,10 +43,7 @@ public DefaultHttpContextFactory(IServiceProvider serviceProvider) /// An initialized object. public HttpContext Create(IFeatureCollection featureCollection) { - if (featureCollection is null) - { - throw new ArgumentNullException(nameof(featureCollection)); - } + ArgumentNullException.ThrowIfNull(featureCollection); var httpContext = new DefaultHttpContext(featureCollection); Initialize(httpContext, featureCollection); diff --git a/src/Hosting/Hosting/src/Internal/HostingEnvironmentExtensions.cs b/src/Hosting/Hosting/src/Internal/HostingEnvironmentExtensions.cs index 851774be8564..97f342dc0f2e 100644 --- a/src/Hosting/Hosting/src/Internal/HostingEnvironmentExtensions.cs +++ b/src/Hosting/Hosting/src/Internal/HostingEnvironmentExtensions.cs @@ -12,10 +12,7 @@ internal static class HostingEnvironmentExtensions internal static void Initialize(this IHostingEnvironment hostingEnvironment, string contentRootPath, WebHostOptions options) #pragma warning restore CS0618 // Type or member is obsolete { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrEmpty(contentRootPath)) { throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath)); @@ -69,10 +66,7 @@ internal static void Initialize( WebHostOptions options, IHostEnvironment? baseEnvironment = null) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrEmpty(contentRootPath)) { throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath)); diff --git a/src/Hosting/Hosting/src/Internal/WebHost.cs b/src/Hosting/Hosting/src/Internal/WebHost.cs index b1804d2bb862..d02470a0a5e0 100644 --- a/src/Hosting/Hosting/src/Internal/WebHost.cs +++ b/src/Hosting/Hosting/src/Internal/WebHost.cs @@ -52,20 +52,9 @@ public WebHost( IConfiguration config, AggregateException? hostingStartupErrors) { - if (appServices == null) - { - throw new ArgumentNullException(nameof(appServices)); - } - - if (hostingServiceProvider == null) - { - throw new ArgumentNullException(nameof(hostingServiceProvider)); - } - - if (config == null) - { - throw new ArgumentNullException(nameof(config)); - } + ArgumentNullException.ThrowIfNull(appServices); + ArgumentNullException.ThrowIfNull(hostingServiceProvider); + ArgumentNullException.ThrowIfNull(config); _config = config; _hostingStartupErrors = hostingStartupErrors; diff --git a/src/Hosting/Hosting/src/Internal/WebHostOptions.cs b/src/Hosting/Hosting/src/Internal/WebHostOptions.cs index d34cc0f8dbe5..0563e5e2560c 100644 --- a/src/Hosting/Hosting/src/Internal/WebHostOptions.cs +++ b/src/Hosting/Hosting/src/Internal/WebHostOptions.cs @@ -13,10 +13,7 @@ internal sealed class WebHostOptions { public WebHostOptions(IConfiguration primaryConfiguration, IConfiguration? fallbackConfiguration = null, IHostEnvironment? environment = null) { - if (primaryConfiguration is null) - { - throw new ArgumentNullException(nameof(primaryConfiguration)); - } + ArgumentNullException.ThrowIfNull(primaryConfiguration); string? GetConfig(string key) => primaryConfiguration[key] ?? fallbackConfiguration?[key]; diff --git a/src/Hosting/Hosting/src/WebHostBuilder.cs b/src/Hosting/Hosting/src/WebHostBuilder.cs index dc46795d989d..81dc2ffef3df 100644 --- a/src/Hosting/Hosting/src/WebHostBuilder.cs +++ b/src/Hosting/Hosting/src/WebHostBuilder.cs @@ -91,10 +91,7 @@ public IWebHostBuilder UseSetting(string key, string? value) /// The . public IWebHostBuilder ConfigureServices(Action configureServices) { - if (configureServices == null) - { - throw new ArgumentNullException(nameof(configureServices)); - } + ArgumentNullException.ThrowIfNull(configureServices); return ConfigureServices((_, services) => configureServices(services)); } diff --git a/src/Hosting/Hosting/src/WebHostBuilderExtensions.cs b/src/Hosting/Hosting/src/WebHostBuilderExtensions.cs index e7364bd09726..cf924e8750f3 100644 --- a/src/Hosting/Hosting/src/WebHostBuilderExtensions.cs +++ b/src/Hosting/Hosting/src/WebHostBuilderExtensions.cs @@ -30,10 +30,7 @@ public static class WebHostBuilderExtensions /// The . public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action configureApp) { - if (configureApp == null) - { - throw new ArgumentNullException(nameof(configureApp)); - } + ArgumentNullException.ThrowIfNull(configureApp); // Light up the ISupportsStartup implementation if (hostBuilder is ISupportsStartup supportsStartup) @@ -62,10 +59,7 @@ public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action /// The . public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action configureApp) { - if (configureApp == null) - { - throw new ArgumentNullException(nameof(configureApp)); - } + ArgumentNullException.ThrowIfNull(configureApp); // Light up the ISupportsStartup implementation if (hostBuilder is ISupportsStartup supportsStartup) @@ -95,10 +89,7 @@ public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action /// When using the il linker, all public methods of are preserved. This should match the Startup type directly (and not a base type). public static IWebHostBuilder UseStartup<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TStartup>(this IWebHostBuilder hostBuilder, Func startupFactory) where TStartup : class { - if (startupFactory == null) - { - throw new ArgumentNullException(nameof(startupFactory)); - } + ArgumentNullException.ThrowIfNull(startupFactory); // Light up the GenericWebHostBuilder implementation if (hostBuilder is ISupportsStartup supportsStartup) @@ -141,10 +132,7 @@ object GetStartupInstance(IServiceProvider serviceProvider) /// The . public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, [DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType) { - if (startupType == null) - { - throw new ArgumentNullException(nameof(startupType)); - } + ArgumentNullException.ThrowIfNull(startupType); // Light up the GenericWebHostBuilder implementation if (hostBuilder is ISupportsStartup supportsStartup) diff --git a/src/Hosting/Server.IntegrationTesting/src/Deployers/ApplicationDeployerFactory.cs b/src/Hosting/Server.IntegrationTesting/src/Deployers/ApplicationDeployerFactory.cs index f2b1f4933b72..b0ae9a58120f 100644 --- a/src/Hosting/Server.IntegrationTesting/src/Deployers/ApplicationDeployerFactory.cs +++ b/src/Hosting/Server.IntegrationTesting/src/Deployers/ApplicationDeployerFactory.cs @@ -19,15 +19,8 @@ public class ApplicationDeployerFactory /// public static ApplicationDeployer Create(DeploymentParameters deploymentParameters, ILoggerFactory loggerFactory) { - if (deploymentParameters == null) - { - throw new ArgumentNullException(nameof(deploymentParameters)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(deploymentParameters); + ArgumentNullException.ThrowIfNull(loggerFactory); switch (deploymentParameters.ServerType) { diff --git a/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs b/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs index 3140eb4c1f6b..f72a881fb886 100644 --- a/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs +++ b/src/Hosting/Server.IntegrationTesting/src/Deployers/RemoteWindowsDeployer/RemoteWindowsDeployer.cs @@ -76,7 +76,7 @@ public override async Task DeployAsync() { if (_isDisposed) { - throw new ObjectDisposedException("This instance of deployer has already been disposed."); + throw new ObjectDisposedException(GetType().Name, "This instance of deployer has already been disposed."); } // Publish the app to a local temp folder on the machine where the test is running diff --git a/src/Hosting/TestHost/src/ClientHandler.cs b/src/Hosting/TestHost/src/ClientHandler.cs index becc8b0b16bd..b6a4b5f5ec9d 100644 --- a/src/Hosting/TestHost/src/ClientHandler.cs +++ b/src/Hosting/TestHost/src/ClientHandler.cs @@ -75,10 +75,7 @@ protected override async Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); var contextBuilder = new HttpContextBuilder(_application, AllowSynchronousIO, PreserveExecutionContext); diff --git a/src/Hosting/TestHost/src/HttpContextBuilder.cs b/src/Hosting/TestHost/src/HttpContextBuilder.cs index 87f9d889c5a8..87d408feaa70 100644 --- a/src/Hosting/TestHost/src/HttpContextBuilder.cs +++ b/src/Hosting/TestHost/src/HttpContextBuilder.cs @@ -60,20 +60,14 @@ internal HttpContextBuilder(ApplicationWrapper application, bool allowSynchronou internal void Configure(Action configureContext) { - if (configureContext == null) - { - throw new ArgumentNullException(nameof(configureContext)); - } + ArgumentNullException.ThrowIfNull(configureContext); configureContext(_httpContext, _requestPipe.Reader); } internal void SendRequestStream(Func sendRequestStream) { - if (sendRequestStream == null) - { - throw new ArgumentNullException(nameof(sendRequestStream)); - } + ArgumentNullException.ThrowIfNull(sendRequestStream); _sendRequestStream = sendRequestStream; } diff --git a/src/Hosting/TestHost/src/RequestBuilder.cs b/src/Hosting/TestHost/src/RequestBuilder.cs index c477bb97aa85..4558cd304b82 100644 --- a/src/Hosting/TestHost/src/RequestBuilder.cs +++ b/src/Hosting/TestHost/src/RequestBuilder.cs @@ -35,10 +35,7 @@ public RequestBuilder(TestServer server, string path) /// This for chaining. public RequestBuilder And(Action configure) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); configure(_req); return this; diff --git a/src/Hosting/TestHost/src/TestServer.cs b/src/Hosting/TestHost/src/TestServer.cs index 6c3c14bb1d1a..1c9c295406ee 100644 --- a/src/Hosting/TestHost/src/TestServer.cs +++ b/src/Hosting/TestHost/src/TestServer.cs @@ -90,10 +90,7 @@ public TestServer(IWebHostBuilder builder) /// public TestServer(IWebHostBuilder builder, IFeatureCollection featureCollection) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); Features = featureCollection ?? throw new ArgumentNullException(nameof(featureCollection)); @@ -209,10 +206,7 @@ public RequestBuilder CreateRequest(string path) /// public async Task SendAsync(Action configureContext, CancellationToken cancellationToken = default) { - if (configureContext == null) - { - throw new ArgumentNullException(nameof(configureContext)); - } + ArgumentNullException.ThrowIfNull(configureContext); var builder = new HttpContextBuilder(Application, AllowSynchronousIO, PreserveExecutionContext); builder.Configure((context, reader) => diff --git a/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs b/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs index e2a9ba0d6d0c..cbdb7e06e989 100644 --- a/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs +++ b/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs @@ -74,15 +74,8 @@ public static HttpClient GetTestClient(this IWebHost host) /// The . public static IWebHostBuilder ConfigureTestServices(this IWebHostBuilder webHostBuilder, Action servicesConfiguration) { - if (webHostBuilder == null) - { - throw new ArgumentNullException(nameof(webHostBuilder)); - } - - if (servicesConfiguration == null) - { - throw new ArgumentNullException(nameof(servicesConfiguration)); - } + ArgumentNullException.ThrowIfNull(webHostBuilder); + ArgumentNullException.ThrowIfNull(servicesConfiguration); if (webHostBuilder.GetType().Name.Equals("GenericWebHostBuilder", StringComparison.Ordinal)) { @@ -110,15 +103,8 @@ public static IWebHostBuilder ConfigureTestServices(this IWebHostBuilder webHost /// public static IWebHostBuilder ConfigureTestContainer(this IWebHostBuilder webHostBuilder, Action servicesConfiguration) { - if (webHostBuilder == null) - { - throw new ArgumentNullException(nameof(webHostBuilder)); - } - - if (servicesConfiguration == null) - { - throw new ArgumentNullException(nameof(servicesConfiguration)); - } + ArgumentNullException.ThrowIfNull(webHostBuilder); + ArgumentNullException.ThrowIfNull(servicesConfiguration); #pragma warning disable CS0612 // Type or member is obsolete webHostBuilder.ConfigureServices( @@ -160,15 +146,8 @@ public static IWebHostBuilder UseSolutionRelativeContentRoot( string applicationBasePath, string solutionName = "*.sln") { - if (solutionRelativePath == null) - { - throw new ArgumentNullException(nameof(solutionRelativePath)); - } - - if (applicationBasePath == null) - { - throw new ArgumentNullException(nameof(applicationBasePath)); - } + ArgumentNullException.ThrowIfNull(solutionRelativePath); + ArgumentNullException.ThrowIfNull(applicationBasePath); var directoryInfo = new DirectoryInfo(applicationBasePath); do @@ -195,10 +174,7 @@ private sealed class ConfigureTestServicesStartupConfigureServicesFilter : IStar public ConfigureTestServicesStartupConfigureServicesFilter(Action servicesConfiguration) { - if (servicesConfiguration == null) - { - throw new ArgumentNullException(nameof(servicesConfiguration)); - } + ArgumentNullException.ThrowIfNull(servicesConfiguration); _servicesConfiguration = servicesConfiguration; } @@ -219,10 +195,7 @@ private sealed class ConfigureTestServicesStartupConfigureContainerFilter containerConfiguration) { - if (containerConfiguration == null) - { - throw new ArgumentNullException(nameof(containerConfiguration)); - } + ArgumentNullException.ThrowIfNull(containerConfiguration); _servicesConfiguration = containerConfiguration; } diff --git a/src/Html.Abstractions/src/HtmlContentBuilder.cs b/src/Html.Abstractions/src/HtmlContentBuilder.cs index 05b28fc3f5e2..c41b7207d2ef 100644 --- a/src/Html.Abstractions/src/HtmlContentBuilder.cs +++ b/src/Html.Abstractions/src/HtmlContentBuilder.cs @@ -42,10 +42,7 @@ public HtmlContentBuilder(int capacity) /// public HtmlContentBuilder(IList entries) { - if (entries == null) - { - throw new ArgumentNullException(nameof(entries)); - } + ArgumentNullException.ThrowIfNull(entries); Entries = entries; } @@ -103,10 +100,7 @@ public IHtmlContentBuilder Clear() /// public void CopyTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); var count = Entries.Count; for (var i = 0; i < count; i++) @@ -133,10 +127,7 @@ public void CopyTo(IHtmlContentBuilder destination) /// public void MoveTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); var count = Entries.Count; for (var i = 0; i < count; i++) @@ -165,15 +156,8 @@ public void MoveTo(IHtmlContentBuilder destination) /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); var count = Entries.Count; for (var i = 0; i < count; i++) diff --git a/src/Html.Abstractions/src/HtmlContentBuilderExtensions.cs b/src/Html.Abstractions/src/HtmlContentBuilderExtensions.cs index 202893e162cf..a13fc0075d07 100644 --- a/src/Html.Abstractions/src/HtmlContentBuilderExtensions.cs +++ b/src/Html.Abstractions/src/HtmlContentBuilderExtensions.cs @@ -29,20 +29,9 @@ public static IHtmlContentBuilder AppendFormat( [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] args) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(args); builder.AppendHtml(new HtmlFormattableString(format, args)); return builder; @@ -69,20 +58,9 @@ public static IHtmlContentBuilder AppendFormat( [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] args) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(args); builder.AppendHtml(new HtmlFormattableString(formatProvider, format, args)); return builder; @@ -95,10 +73,7 @@ public static IHtmlContentBuilder AppendFormat( /// The . public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AppendHtml(HtmlString.NewLine); return builder; @@ -113,10 +88,7 @@ public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder) /// The . public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, string unencoded) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Append(unencoded); builder.AppendHtml(HtmlString.NewLine); @@ -131,10 +103,7 @@ public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, s /// The . public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, IHtmlContent content) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AppendHtml(content); builder.AppendHtml(HtmlString.NewLine); @@ -150,10 +119,7 @@ public static IHtmlContentBuilder AppendLine(this IHtmlContentBuilder builder, I /// The . public static IHtmlContentBuilder AppendHtmlLine(this IHtmlContentBuilder builder, string encoded) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AppendHtml(encoded); builder.AppendHtml(HtmlString.NewLine); @@ -169,10 +135,7 @@ public static IHtmlContentBuilder AppendHtmlLine(this IHtmlContentBuilder builde /// The . public static IHtmlContentBuilder SetContent(this IHtmlContentBuilder builder, string unencoded) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Clear(); builder.Append(unencoded); @@ -187,10 +150,7 @@ public static IHtmlContentBuilder SetContent(this IHtmlContentBuilder builder, s /// The . public static IHtmlContentBuilder SetHtmlContent(this IHtmlContentBuilder builder, IHtmlContent content) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Clear(); builder.AppendHtml(content); @@ -206,10 +166,7 @@ public static IHtmlContentBuilder SetHtmlContent(this IHtmlContentBuilder builde /// The . public static IHtmlContentBuilder SetHtmlContent(this IHtmlContentBuilder builder, string encoded) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Clear(); builder.AppendHtml(encoded); diff --git a/src/Html.Abstractions/src/HtmlFormattableString.cs b/src/Html.Abstractions/src/HtmlFormattableString.cs index 0de6d6482b6a..f1ce14915676 100644 --- a/src/Html.Abstractions/src/HtmlFormattableString.cs +++ b/src/Html.Abstractions/src/HtmlFormattableString.cs @@ -43,15 +43,8 @@ public HtmlFormattableString( [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] args) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(args); _formatProvider = formatProvider ?? CultureInfo.CurrentCulture; _format = format; @@ -61,15 +54,8 @@ public HtmlFormattableString( /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); var formatProvider = new EncodingFormatProvider(_formatProvider, encoder); writer.Write(string.Format(formatProvider, _format, _args)); diff --git a/src/Html.Abstractions/src/HtmlString.cs b/src/Html.Abstractions/src/HtmlString.cs index e777c9849d3a..39df58cb3777 100644 --- a/src/Html.Abstractions/src/HtmlString.cs +++ b/src/Html.Abstractions/src/HtmlString.cs @@ -37,15 +37,8 @@ public HtmlString(string? value) /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); writer.Write(Value); } diff --git a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs index 298a18eceaf8..7477d2ba7fdc 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs @@ -78,10 +78,7 @@ public AuthenticateResult Clone() /// The result. public static AuthenticateResult Success(AuthenticationTicket ticket) { - if (ticket == null) - { - throw new ArgumentNullException(nameof(ticket)); - } + ArgumentNullException.ThrowIfNull(ticket); return new AuthenticateResult() { Ticket = ticket, Properties = ticket.Properties }; } diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationOptions.cs b/src/Http/Authentication.Abstractions/src/AuthenticationOptions.cs index 391a3ac42d60..1306e4b38b2c 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationOptions.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationOptions.cs @@ -31,14 +31,9 @@ public class AuthenticationOptions /// Configures the scheme. public void AddScheme(string name, Action configureBuilder) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (configureBuilder == null) - { - throw new ArgumentNullException(nameof(configureBuilder)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configureBuilder); + if (SchemeMap.ContainsKey(name)) { throw new InvalidOperationException("Scheme already exists: " + name); diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationScheme.cs b/src/Http/Authentication.Abstractions/src/AuthenticationScheme.cs index 2a349ec6b8e8..c64d48bc480b 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationScheme.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationScheme.cs @@ -19,14 +19,8 @@ public class AuthenticationScheme /// The type that handles this scheme. public AuthenticationScheme(string name, string? displayName, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type handlerType) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (handlerType == null) - { - throw new ArgumentNullException(nameof(handlerType)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(handlerType); if (!typeof(IAuthenticationHandler).IsAssignableFrom(handlerType)) { throw new ArgumentException("handlerType must implement IAuthenticationHandler."); diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs b/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs index 72bdd9388e19..40a44bacefa1 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs @@ -18,10 +18,7 @@ public class AuthenticationTicket /// the authentication scheme that was responsible for this ticket. public AuthenticationTicket(ClaimsPrincipal principal, AuthenticationProperties? properties, string authenticationScheme) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullException.ThrowIfNull(principal); AuthenticationScheme = authenticationScheme; Principal = principal; diff --git a/src/Http/Authentication.Abstractions/src/TokenExtensions.cs b/src/Http/Authentication.Abstractions/src/TokenExtensions.cs index 06b82767ab14..6a353c5a1096 100644 --- a/src/Http/Authentication.Abstractions/src/TokenExtensions.cs +++ b/src/Http/Authentication.Abstractions/src/TokenExtensions.cs @@ -20,14 +20,8 @@ public static class AuthenticationTokenExtensions /// The tokens to store. public static void StoreTokens(this AuthenticationProperties properties, IEnumerable tokens) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - if (tokens == null) - { - throw new ArgumentNullException(nameof(tokens)); - } + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(tokens); // Clear old tokens first var oldTokens = properties.GetTokens(); @@ -63,14 +57,8 @@ public static void StoreTokens(this AuthenticationProperties properties, IEnumer /// The token value. public static string? GetTokenValue(this AuthenticationProperties properties, string tokenName) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(tokenName); var tokenKey = TokenKeyPrefix + tokenName; @@ -86,14 +74,8 @@ public static void StoreTokens(this AuthenticationProperties properties, IEnumer /// if the token was updated, otherwise . public static bool UpdateTokenValue(this AuthenticationProperties properties, string tokenName, string tokenValue) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullException.ThrowIfNull(properties); + ArgumentNullException.ThrowIfNull(tokenName); var tokenKey = TokenKeyPrefix + tokenName; if (!properties.Items.ContainsKey(tokenKey)) @@ -111,10 +93,7 @@ public static bool UpdateTokenValue(this AuthenticationProperties properties, st /// The authentication tokens. public static IEnumerable GetTokens(this AuthenticationProperties properties) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } + ArgumentNullException.ThrowIfNull(properties); var tokens = new List(); if (properties.Items.TryGetValue(TokenNamesKey, out var value) && !string.IsNullOrEmpty(value)) @@ -153,14 +132,8 @@ public static IEnumerable GetTokens(this AuthenticationProp /// The value of the token if present. public static async Task GetTokenAsync(this IAuthenticationService auth, HttpContext context, string? scheme, string tokenName) { - if (auth == null) - { - throw new ArgumentNullException(nameof(auth)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullException.ThrowIfNull(auth); + ArgumentNullException.ThrowIfNull(tokenName); var result = await auth.AuthenticateAsync(context, scheme); return result?.Properties?.GetTokenValue(tokenName); diff --git a/src/Http/Authentication.Core/src/AuthenticationCoreServiceCollectionExtensions.cs b/src/Http/Authentication.Core/src/AuthenticationCoreServiceCollectionExtensions.cs index fc844b0dae5a..9b73616527ba 100644 --- a/src/Http/Authentication.Core/src/AuthenticationCoreServiceCollectionExtensions.cs +++ b/src/Http/Authentication.Core/src/AuthenticationCoreServiceCollectionExtensions.cs @@ -18,10 +18,7 @@ public static class AuthenticationCoreServiceCollectionExtensions /// The service collection. public static IServiceCollection AddAuthenticationCore(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddScoped(); services.TryAddSingleton(); // Can be replaced with scoped ones that use DbContext @@ -38,15 +35,8 @@ public static IServiceCollection AddAuthenticationCore(this IServiceCollection s /// The service collection. public static IServiceCollection AddAuthenticationCore(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddAuthenticationCore(); services.Configure(configureOptions); diff --git a/src/Http/Authentication.Core/src/AuthenticationService.cs b/src/Http/Authentication.Core/src/AuthenticationService.cs index e949edcfac57..027886286ef3 100644 --- a/src/Http/Authentication.Core/src/AuthenticationService.cs +++ b/src/Http/Authentication.Core/src/AuthenticationService.cs @@ -163,10 +163,7 @@ public virtual async Task ForbidAsync(HttpContext context, string? scheme, Authe /// A task. public virtual async Task SignInAsync(HttpContext context, string? scheme, ClaimsPrincipal principal, AuthenticationProperties? properties) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullException.ThrowIfNull(principal); if (Options.RequireAuthenticatedSignIn) { diff --git a/src/Http/Headers/src/ContentDispositionHeaderValueIdentityExtensions.cs b/src/Http/Headers/src/ContentDispositionHeaderValueIdentityExtensions.cs index 6e1e4621bb1e..a712e4a1131c 100644 --- a/src/Http/Headers/src/ContentDispositionHeaderValueIdentityExtensions.cs +++ b/src/Http/Headers/src/ContentDispositionHeaderValueIdentityExtensions.cs @@ -17,10 +17,7 @@ public static class ContentDispositionHeaderValueIdentityExtensions /// True if the header is file disposition, false otherwise public static bool IsFileDisposition(this ContentDispositionHeaderValue header) { - if (header == null) - { - throw new ArgumentNullException(nameof(header)); - } + ArgumentNullException.ThrowIfNull(header); return header.DispositionType.Equals("form-data") && (!StringSegment.IsNullOrEmpty(header.FileName) || !StringSegment.IsNullOrEmpty(header.FileNameStar)); @@ -33,10 +30,7 @@ public static bool IsFileDisposition(this ContentDispositionHeaderValue header) /// True if the header is form disposition, false otherwise public static bool IsFormDisposition(this ContentDispositionHeaderValue header) { - if (header == null) - { - throw new ArgumentNullException(nameof(header)); - } + ArgumentNullException.ThrowIfNull(header); return header.DispositionType.Equals("form-data") && StringSegment.IsNullOrEmpty(header.FileName) && StringSegment.IsNullOrEmpty(header.FileNameStar); diff --git a/src/Http/Headers/src/ContentRangeHeaderValue.cs b/src/Http/Headers/src/ContentRangeHeaderValue.cs index 1d481f6ebb30..4d1ba24ce054 100644 --- a/src/Http/Headers/src/ContentRangeHeaderValue.cs +++ b/src/Http/Headers/src/ContentRangeHeaderValue.cs @@ -34,10 +34,7 @@ public ContentRangeHeaderValue(long from, long to, long length) { // Scenario: "Content-Range: bytes 12-34/5678" - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length)); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); if ((to < 0) || (to > length)) { throw new ArgumentOutOfRangeException(nameof(to)); @@ -61,10 +58,7 @@ public ContentRangeHeaderValue(long length) { // Scenario: "Content-Range: bytes */1234" - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length)); - } + ArgumentOutOfRangeException.ThrowIfNegative(length); Length = length; _unit = HeaderUtilities.BytesUnit; @@ -79,10 +73,7 @@ public ContentRangeHeaderValue(long from, long to) { // Scenario: "Content-Range: bytes 12-34/*" - if (to < 0) - { - throw new ArgumentOutOfRangeException(nameof(to)); - } + ArgumentOutOfRangeException.ThrowIfNegative(to); if ((from < 0) || (from > to)) { throw new ArgumentOutOfRangeException(nameof(@from)); diff --git a/src/Http/Headers/src/GenericHeaderParser.cs b/src/Http/Headers/src/GenericHeaderParser.cs index 534cdde67c36..a309cda3a9a4 100644 --- a/src/Http/Headers/src/GenericHeaderParser.cs +++ b/src/Http/Headers/src/GenericHeaderParser.cs @@ -14,10 +14,7 @@ internal sealed class GenericHeaderParser : BaseHeaderParser internal GenericHeaderParser(bool supportsMultipleValues, GetParsedValueLengthDelegate getParsedValueLength) : base(supportsMultipleValues) { - if (getParsedValueLength == null) - { - throw new ArgumentNullException(nameof(getParsedValueLength)); - } + ArgumentNullException.ThrowIfNull(getParsedValueLength); _getParsedValueLength = getParsedValueLength; } diff --git a/src/Http/Headers/src/RangeConditionHeaderValue.cs b/src/Http/Headers/src/RangeConditionHeaderValue.cs index 6f30f77f11ed..802871855bcb 100644 --- a/src/Http/Headers/src/RangeConditionHeaderValue.cs +++ b/src/Http/Headers/src/RangeConditionHeaderValue.cs @@ -38,10 +38,7 @@ public RangeConditionHeaderValue(DateTimeOffset lastModified) /// An entity tag uniquely representing the requested resource. public RangeConditionHeaderValue(EntityTagHeaderValue entityTag) { - if (entityTag == null) - { - throw new ArgumentNullException(nameof(entityTag)); - } + ArgumentNullException.ThrowIfNull(entityTag); _entityTag = entityTag; } diff --git a/src/Http/Headers/src/StringWithQualityHeaderValueComparer.cs b/src/Http/Headers/src/StringWithQualityHeaderValueComparer.cs index 4d7b8dd593f9..4d12959e68e9 100644 --- a/src/Http/Headers/src/StringWithQualityHeaderValueComparer.cs +++ b/src/Http/Headers/src/StringWithQualityHeaderValueComparer.cs @@ -38,15 +38,8 @@ public int Compare( StringWithQualityHeaderValue? stringWithQuality1, StringWithQualityHeaderValue? stringWithQuality2) { - if (stringWithQuality1 == null) - { - throw new ArgumentNullException(nameof(stringWithQuality1)); - } - - if (stringWithQuality2 == null) - { - throw new ArgumentNullException(nameof(stringWithQuality2)); - } + ArgumentNullException.ThrowIfNull(stringWithQuality1); + ArgumentNullException.ThrowIfNull(stringWithQuality2); var quality1 = stringWithQuality1.Quality ?? HeaderQuality.Match; var quality2 = stringWithQuality2.Quality ?? HeaderQuality.Match; diff --git a/src/Http/Http.Abstractions/src/CookieBuilder.cs b/src/Http/Http.Abstractions/src/CookieBuilder.cs index 8e2c0d462824..f846008d5444 100644 --- a/src/Http/Http.Abstractions/src/CookieBuilder.cs +++ b/src/Http/Http.Abstractions/src/CookieBuilder.cs @@ -104,10 +104,7 @@ public IList Extensions /// The cookie options. public virtual CookieOptions Build(HttpContext context, DateTimeOffset expiresFrom) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var options = new CookieOptions { diff --git a/src/Http/Http.Abstractions/src/Extensions/HttpResponseWritingExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/HttpResponseWritingExtensions.cs index bbfb6b7ad510..e5f02b1d8029 100644 --- a/src/Http/Http.Abstractions/src/Extensions/HttpResponseWritingExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/HttpResponseWritingExtensions.cs @@ -25,15 +25,8 @@ public static class HttpResponseWritingExtensions [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsync(this HttpResponse response, string text, CancellationToken cancellationToken = default(CancellationToken)) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (text == null) - { - throw new ArgumentNullException(nameof(text)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(text); return response.WriteAsync(text, Encoding.UTF8, cancellationToken); } @@ -49,20 +42,9 @@ public static class HttpResponseWritingExtensions [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task WriteAsync(this HttpResponse response, string text, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (text == null) - { - throw new ArgumentNullException(nameof(text)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(text); + ArgumentNullException.ThrowIfNull(encoding); // Need to call StartAsync before GetMemory/GetSpan if (!response.HasStarted) diff --git a/src/Http/Http.Abstractions/src/Extensions/MapExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/MapExtensions.cs index 75544c3f770f..0f990846468c 100644 --- a/src/Http/Http.Abstractions/src/Extensions/MapExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/MapExtensions.cs @@ -48,15 +48,8 @@ public static IApplicationBuilder Map(this IApplicationBuilder app, PathString p /// The instance. public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, bool preserveMatchedPathSegment, Action configuration) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(configuration); if (pathMatch.HasValue && pathMatch.Value!.EndsWith('/')) { diff --git a/src/Http/Http.Abstractions/src/Extensions/MapMiddleware.cs b/src/Http/Http.Abstractions/src/Extensions/MapMiddleware.cs index 382efd21c3a2..24edc1efc1c3 100644 --- a/src/Http/Http.Abstractions/src/Extensions/MapMiddleware.cs +++ b/src/Http/Http.Abstractions/src/Extensions/MapMiddleware.cs @@ -20,15 +20,8 @@ public class MapMiddleware /// The middleware options. public MapMiddleware(RequestDelegate next, MapOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); if (options.Branch == null) { @@ -46,10 +39,7 @@ public MapMiddleware(RequestDelegate next, MapOptions options) /// A task that represents the execution of this middleware. public Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Request.Path.StartsWithSegments(_options.PathMatch, out var matchedPath, out var remainingPath)) { diff --git a/src/Http/Http.Abstractions/src/Extensions/MapWhenExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/MapWhenExtensions.cs index e5b77a919409..2fea33752ce7 100644 --- a/src/Http/Http.Abstractions/src/Extensions/MapWhenExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/MapWhenExtensions.cs @@ -22,20 +22,9 @@ public static class MapWhenExtensions /// public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action configuration) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (predicate == null) - { - throw new ArgumentNullException(nameof(predicate)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(configuration); // create branch var branchBuilder = app.New(); diff --git a/src/Http/Http.Abstractions/src/Extensions/MapWhenMiddleware.cs b/src/Http/Http.Abstractions/src/Extensions/MapWhenMiddleware.cs index ce275eb41617..8a69f3cdd8ef 100644 --- a/src/Http/Http.Abstractions/src/Extensions/MapWhenMiddleware.cs +++ b/src/Http/Http.Abstractions/src/Extensions/MapWhenMiddleware.cs @@ -20,15 +20,8 @@ public class MapWhenMiddleware /// The middleware options. public MapWhenMiddleware(RequestDelegate next, MapWhenOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); if (options.Predicate == null) { @@ -51,10 +44,7 @@ public MapWhenMiddleware(RequestDelegate next, MapWhenOptions options) /// A task that represents the execution of this middleware. public Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (_options.Predicate!(context)) { diff --git a/src/Http/Http.Abstractions/src/Extensions/MapWhenOptions.cs b/src/Http/Http.Abstractions/src/Extensions/MapWhenOptions.cs index fb1690679c6f..962acbd23e75 100644 --- a/src/Http/Http.Abstractions/src/Extensions/MapWhenOptions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/MapWhenOptions.cs @@ -23,10 +23,7 @@ public Func? Predicate } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _predicate = value; } diff --git a/src/Http/Http.Abstractions/src/Extensions/RunExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/RunExtensions.cs index 521e56dba6c3..d0fb02958ddb 100644 --- a/src/Http/Http.Abstractions/src/Extensions/RunExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/RunExtensions.cs @@ -17,15 +17,8 @@ public static class RunExtensions /// A delegate that handles the request. public static void Run(this IApplicationBuilder app, RequestDelegate handler) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(handler); app.Use(_ => handler); } diff --git a/src/Http/Http.Abstractions/src/Extensions/UsePathBaseExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/UsePathBaseExtensions.cs index 254f88211cbe..02fdb713b0fd 100644 --- a/src/Http/Http.Abstractions/src/Extensions/UsePathBaseExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/UsePathBaseExtensions.cs @@ -20,10 +20,7 @@ public static class UsePathBaseExtensions /// The instance. public static IApplicationBuilder UsePathBase(this IApplicationBuilder app, PathString pathBase) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); // Strip trailing slashes pathBase = new PathString(pathBase.Value?.TrimEnd('/')); diff --git a/src/Http/Http.Abstractions/src/Extensions/UsePathBaseMiddleware.cs b/src/Http/Http.Abstractions/src/Extensions/UsePathBaseMiddleware.cs index 0069bea7801f..aaba6a0d571d 100644 --- a/src/Http/Http.Abstractions/src/Extensions/UsePathBaseMiddleware.cs +++ b/src/Http/Http.Abstractions/src/Extensions/UsePathBaseMiddleware.cs @@ -20,10 +20,7 @@ public class UsePathBaseMiddleware /// The path base to extract. public UsePathBaseMiddleware(RequestDelegate next, PathString pathBase) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(next); if (!pathBase.HasValue) { @@ -41,10 +38,7 @@ public UsePathBaseMiddleware(RequestDelegate next, PathString pathBase) /// A task that represents the execution of this middleware. public Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Request.Path.StartsWithSegments(_pathBase, out var matchedPath, out var remainingPath)) { diff --git a/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs b/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs index f52eadd0f786..d7b5c2f7c1f6 100644 --- a/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs +++ b/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs @@ -21,20 +21,9 @@ public static class UseWhenExtensions /// public static IApplicationBuilder UseWhen(this IApplicationBuilder app, Predicate predicate, Action configuration) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (predicate == null) - { - throw new ArgumentNullException(nameof(predicate)); - } - - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(predicate); + ArgumentNullException.ThrowIfNull(configuration); // Create and configure the branch builder right away; otherwise, // we would end up running our branch after all the components diff --git a/src/Http/Http.Abstractions/src/FragmentString.cs b/src/Http/Http.Abstractions/src/FragmentString.cs index b41fcffdc56b..21cdd430a22c 100644 --- a/src/Http/Http.Abstractions/src/FragmentString.cs +++ b/src/Http/Http.Abstractions/src/FragmentString.cs @@ -90,10 +90,7 @@ public static FragmentString FromUriComponent(string uriComponent) /// The resulting FragmentString public static FragmentString FromUriComponent(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); string fragmentValue = uri.GetComponents(UriComponents.Fragment, UriFormat.UriEscaped); if (!string.IsNullOrEmpty(fragmentValue)) diff --git a/src/Http/Http.Abstractions/src/HostString.cs b/src/Http/Http.Abstractions/src/HostString.cs index 46e7454e9479..d883e6c591d0 100644 --- a/src/Http/Http.Abstractions/src/HostString.cs +++ b/src/Http/Http.Abstractions/src/HostString.cs @@ -32,10 +32,7 @@ public HostString(string value) /// A positive, greater than 0 value representing the port in the host string. public HostString(string host, int port) { - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } + ArgumentNullException.ThrowIfNull(host); if (port <= 0) { @@ -200,10 +197,7 @@ public static HostString FromUriComponent(string uriComponent) /// The that was created. public static HostString FromUriComponent(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); return new HostString(uri.GetComponents( UriComponents.NormalizedHost | // Always convert punycode to Unicode. @@ -231,10 +225,7 @@ public static bool MatchesAny(StringSegment value, IList patterns { throw new ArgumentNullException(nameof(value)); } - if (patterns == null) - { - throw new ArgumentNullException(nameof(patterns)); - } + ArgumentNullException.ThrowIfNull(patterns); // Drop the port GetParts(value, out var host, out var port); diff --git a/src/Http/Http.Abstractions/src/HttpProtocol.cs b/src/Http/Http.Abstractions/src/HttpProtocol.cs index cb8563617ed8..0c8ff3fcf928 100644 --- a/src/Http/Http.Abstractions/src/HttpProtocol.cs +++ b/src/Http/Http.Abstractions/src/HttpProtocol.cs @@ -109,10 +109,7 @@ public static bool IsHttp3(string protocol) /// A HTTP request protocol. public static string GetHttpProtocol(Version version) { - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } + ArgumentNullException.ThrowIfNull(version); return version switch { diff --git a/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs b/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs index e8e7b59f3f6b..a3e804306816 100644 --- a/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs +++ b/src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs @@ -37,10 +37,7 @@ public static StringValues GetHeaderSplit(IHeaderDictionary headers, string key) public static StringValues GetHeaderUnmodified(IHeaderDictionary headers, string key) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); StringValues values; return headers.TryGetValue(key, out values) ? values : StringValues.Empty; @@ -48,10 +45,7 @@ public static StringValues GetHeaderUnmodified(IHeaderDictionary headers, string public static void SetHeaderJoined(IHeaderDictionary headers, string key, StringValues value) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); if (string.IsNullOrEmpty(key)) { @@ -92,10 +86,7 @@ public static void SetHeaderJoined(IHeaderDictionary headers, string key, String public static void SetHeaderUnmodified(IHeaderDictionary headers, string key, StringValues? values) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); if (string.IsNullOrEmpty(key)) { @@ -113,15 +104,8 @@ public static void SetHeaderUnmodified(IHeaderDictionary headers, string key, St public static void AppendHeaderJoined(IHeaderDictionary headers, string key, params string[] values) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(key); if (values == null || values.Length == 0) { @@ -141,15 +125,8 @@ public static void AppendHeaderJoined(IHeaderDictionary headers, string key, par public static void AppendHeaderUnmodified(IHeaderDictionary headers, string key, StringValues values) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(key); if (values.Count == 0) { diff --git a/src/Http/Http.Abstractions/src/PathString.cs b/src/Http/Http.Abstractions/src/PathString.cs index f5f34da7e97b..0adf8cc2ef81 100644 --- a/src/Http/Http.Abstractions/src/PathString.cs +++ b/src/Http/Http.Abstractions/src/PathString.cs @@ -193,10 +193,7 @@ public static PathString FromUriComponent(string uriComponent) /// The resulting PathString public static PathString FromUriComponent(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); var uriComponent = uri.GetComponents(UriComponents.Path, UriFormat.UriEscaped); Span pathBuffer = uriComponent.Length < StackAllocThreshold ? stackalloc char[StackAllocThreshold] : new char[uriComponent.Length + 1]; pathBuffer[0] = '/'; @@ -484,10 +481,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } + ArgumentNullException.ThrowIfNull(destinationType); return destinationType == typeof(string) ? value?.ToString() ?? string.Empty diff --git a/src/Http/Http.Abstractions/src/QueryString.cs b/src/Http/Http.Abstractions/src/QueryString.cs index 4df2197e7286..657422155bca 100644 --- a/src/Http/Http.Abstractions/src/QueryString.cs +++ b/src/Http/Http.Abstractions/src/QueryString.cs @@ -86,10 +86,7 @@ public static QueryString FromUriComponent(string uriComponent) /// The resulting QueryString public static QueryString FromUriComponent(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); string queryValue = uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped); if (!string.IsNullOrEmpty(queryValue)) @@ -107,10 +104,7 @@ public static QueryString FromUriComponent(Uri uri) /// The resulting QueryString public static QueryString Create(string name, string value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (!string.IsNullOrEmpty(value)) { @@ -196,10 +190,7 @@ public QueryString Add(QueryString other) /// The concatenated . public QueryString Add(string name, string value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (!HasValue || Value!.Equals("?", StringComparison.Ordinal)) { diff --git a/src/Http/Http.Abstractions/src/Routing/EndpointHttpContextExtensions.cs b/src/Http/Http.Abstractions/src/Routing/EndpointHttpContextExtensions.cs index 8af9ed0b0ea8..dc309201494f 100644 --- a/src/Http/Http.Abstractions/src/Routing/EndpointHttpContextExtensions.cs +++ b/src/Http/Http.Abstractions/src/Routing/EndpointHttpContextExtensions.cs @@ -17,10 +17,7 @@ public static class EndpointHttpContextExtensions /// The . public static Endpoint? GetEndpoint(this HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return context.Features.Get()?.Endpoint; } @@ -32,10 +29,7 @@ public static class EndpointHttpContextExtensions /// The . public static void SetEndpoint(this HttpContext context, Endpoint? endpoint) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var feature = context.Features.Get(); diff --git a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs index 5e3dc1b77d1c..567a35aa1ffa 100644 --- a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs +++ b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs @@ -32,10 +32,7 @@ public sealed class EndpointMetadataCollection : IReadOnlyList /// The metadata items. public EndpointMetadataCollection(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); _items = items.ToArray(); _cache = new ConcurrentDictionary(); diff --git a/src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs b/src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs index abf2896c88ee..4fd135eb8bf5 100644 --- a/src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs +++ b/src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs @@ -36,10 +36,7 @@ public class RouteValueDictionary : IDictionary, IReadOnlyDicti /// A new . public static RouteValueDictionary FromArray(KeyValuePair[] items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); // We need to compress the array by removing non-contiguous items. We // typically have a very small number of items to process. We don't need @@ -406,10 +403,7 @@ private bool ContainsKeyCore(string key) KeyValuePair[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0 || arrayIndex > array.Length || array.Length - arrayIndex < this.Count) { @@ -749,10 +743,7 @@ public struct Enumerator : IEnumerator> /// A . public Enumerator(RouteValueDictionary dictionary) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } + ArgumentNullException.ThrowIfNull(dictionary); _dictionary = dictionary; diff --git a/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs b/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs index fcc8b91c8f29..cc6d2b8eb5b7 100644 --- a/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs +++ b/src/Http/Http.Extensions/src/HeaderDictionaryTypeExtensions.cs @@ -41,30 +41,16 @@ public static ResponseHeaders GetTypedHeaders(this HttpResponse response) internal static DateTimeOffset? GetDate(this IHeaderDictionary headers, string name) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(name); return headers.Get(name); } internal static void Set(this IHeaderDictionary headers, string name, object? value) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(name); if (value == null) { @@ -78,15 +64,8 @@ internal static void Set(this IHeaderDictionary headers, string name, object? va internal static void SetList(this IHeaderDictionary headers, string name, IList? values) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(name); if (values == null || values.Count == 0) { @@ -116,15 +95,8 @@ internal static void SetList(this IHeaderDictionary headers, string name, ILi /// The values to append. public static void AppendList(this IHeaderDictionary Headers, string name, IList values) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(values); switch (values.Count) { @@ -147,15 +119,8 @@ public static void AppendList(this IHeaderDictionary Headers, string name, IL internal static void SetDate(this IHeaderDictionary headers, string name, DateTimeOffset? value) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(headers); + ArgumentNullException.ThrowIfNull(name); if (value.HasValue) { @@ -191,10 +156,7 @@ internal static void SetDate(this IHeaderDictionary headers, string name, DateTi internal static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>(this IHeaderDictionary headers, string name) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); var value = headers[name]; @@ -214,10 +176,7 @@ internal static void SetDate(this IHeaderDictionary headers, string name, DateTi internal static IList GetList<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>(this IHeaderDictionary headers, string name) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); var values = headers[name]; diff --git a/src/Http/Http.Extensions/src/HttpRequestJsonExtensions.cs b/src/Http/Http.Extensions/src/HttpRequestJsonExtensions.cs index 38243dccad27..09cc97339d0b 100644 --- a/src/Http/Http.Extensions/src/HttpRequestJsonExtensions.cs +++ b/src/Http/Http.Extensions/src/HttpRequestJsonExtensions.cs @@ -57,10 +57,7 @@ public static class HttpRequestJsonExtensions JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!request.HasJsonContentType(out var charset)) { @@ -100,10 +97,7 @@ public static class HttpRequestJsonExtensions JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!request.HasJsonContentType(out var charset)) { @@ -141,10 +135,7 @@ public static class HttpRequestJsonExtensions JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!request.HasJsonContentType(out var charset)) { @@ -202,14 +193,8 @@ public static class HttpRequestJsonExtensions JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(type); if (!request.HasJsonContentType(out var charset)) { @@ -251,20 +236,9 @@ public static class HttpRequestJsonExtensions JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(context); if (!request.HasJsonContentType(out var charset)) { @@ -298,10 +272,7 @@ public static bool HasJsonContentType(this HttpRequest request) private static bool HasJsonContentType(this HttpRequest request, out StringSegment charset) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mt)) { diff --git a/src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs b/src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs index 0d784ec65638..5846e79e4500 100644 --- a/src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs +++ b/src/Http/Http.Extensions/src/HttpRequestMultipartExtensions.cs @@ -17,10 +17,7 @@ public static class HttpRequestMultipartExtensions /// The multipart boundary. public static string GetMultipartBoundary(this HttpRequest request) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaType)) { diff --git a/src/Http/Http.Extensions/src/HttpResponseJsonExtensions.cs b/src/Http/Http.Extensions/src/HttpResponseJsonExtensions.cs index 87deb07a9b47..9d771adc2fb2 100644 --- a/src/Http/Http.Extensions/src/HttpResponseJsonExtensions.cs +++ b/src/Http/Http.Extensions/src/HttpResponseJsonExtensions.cs @@ -81,10 +81,7 @@ public static Task WriteAsJsonAsync( string? contentType, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } + ArgumentNullException.ThrowIfNull(response); options ??= ResolveSerializerOptions(response.HttpContext); @@ -119,10 +116,7 @@ public static Task WriteAsJsonAsync( string? contentType = default, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } + ArgumentNullException.ThrowIfNull(response); response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset; @@ -163,10 +157,7 @@ public static Task WriteAsJsonAsync( string? contentType = default, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } + ArgumentNullException.ThrowIfNull(response); response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset; @@ -266,14 +257,8 @@ public static Task WriteAsJsonAsync( string? contentType, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(type); options ??= ResolveSerializerOptions(response.HttpContext); @@ -325,20 +310,9 @@ public static Task WriteAsJsonAsync( string? contentType = default, CancellationToken cancellationToken = default) { - if (response is null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(context); response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset; diff --git a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs index f3c60b48473d..c3a10dadb24f 100644 --- a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs +++ b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs @@ -159,10 +159,7 @@ public static RequestDelegateResult Create(Delegate handler, RequestDelegateFact [SuppressMessage("ApiDesign", "RS0027:Public API with optional parameter(s) should have the most parameters amongst its public overloads.", Justification = "Required to maintain compatibility")] public static RequestDelegateResult Create(Delegate handler, RequestDelegateFactoryOptions? options = null, RequestDelegateMetadataResult? metadataResult = null) { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(handler); var targetExpression = handler.Target switch { @@ -214,10 +211,7 @@ public static RequestDelegateResult Create(MethodInfo methodInfo, Func? targetFactory = null, RequestDelegateFactoryOptions? options = null, RequestDelegateMetadataResult? metadataResult = null) { - if (methodInfo is null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(methodInfo); if (methodInfo.DeclaringType is null) { diff --git a/src/Http/Http.Extensions/src/RequestHeaders.cs b/src/Http/Http.Extensions/src/RequestHeaders.cs index d6f6cef97aa4..a42af0982801 100644 --- a/src/Http/Http.Extensions/src/RequestHeaders.cs +++ b/src/Http/Http.Extensions/src/RequestHeaders.cs @@ -18,10 +18,7 @@ public class RequestHeaders /// The request headers. public RequestHeaders(IHeaderDictionary headers) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); Headers = headers; } @@ -383,10 +380,7 @@ public Uri? Referer /// The header value. public void Set(string name, object? value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Headers.Set(name, value); } @@ -399,10 +393,7 @@ public void Set(string name, object? value) /// The sequence of header values. public void SetList(string name, IList? values) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Headers.SetList(name, values); } @@ -414,15 +405,8 @@ public void SetList(string name, IList? values) /// The header value. public void Append(string name, object value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); Headers.Append(name, value.ToString()); } diff --git a/src/Http/Http.Extensions/src/ResponseHeaders.cs b/src/Http/Http.Extensions/src/ResponseHeaders.cs index 74f13b8d7af0..605681727a1c 100644 --- a/src/Http/Http.Extensions/src/ResponseHeaders.cs +++ b/src/Http/Http.Extensions/src/ResponseHeaders.cs @@ -18,10 +18,7 @@ public class ResponseHeaders /// The request headers. public ResponseHeaders(IHeaderDictionary headers) { - if (headers == null) - { - throw new ArgumentNullException(nameof(headers)); - } + ArgumentNullException.ThrowIfNull(headers); Headers = headers; } @@ -233,10 +230,7 @@ public IList SetCookie /// The header value. public void Set(string name, object? value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Headers.Set(name, value); } @@ -249,10 +243,7 @@ public void Set(string name, object? value) /// The sequence of header values. public void SetList(string name, IList? values) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Headers.SetList(name, values); } @@ -264,15 +255,8 @@ public void SetList(string name, IList? values) /// The header value. public void Append(string name, object value) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); Headers.Append(name, value.ToString()); } diff --git a/src/Http/Http.Extensions/src/SendFileResponseExtensions.cs b/src/Http/Http.Extensions/src/SendFileResponseExtensions.cs index 8297e292af3c..3b00124f51b6 100644 --- a/src/Http/Http.Extensions/src/SendFileResponseExtensions.cs +++ b/src/Http/Http.Extensions/src/SendFileResponseExtensions.cs @@ -24,14 +24,8 @@ public static class SendFileResponseExtensions [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendFileAsync(this HttpResponse response, IFileInfo file, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - if (file == null) - { - throw new ArgumentNullException(nameof(file)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(file); return SendFileAsyncCore(response, file, 0, null, cancellationToken); } @@ -48,14 +42,8 @@ public static Task SendFileAsync(this HttpResponse response, IFileInfo file, Can [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendFileAsync(this HttpResponse response, IFileInfo file, long offset, long? count, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - if (file == null) - { - throw new ArgumentNullException(nameof(file)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(file); return SendFileAsyncCore(response, file, offset, count, cancellationToken); } @@ -70,15 +58,8 @@ public static Task SendFileAsync(this HttpResponse response, IFileInfo file, lon [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendFileAsync(this HttpResponse response, string fileName, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (fileName == null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(fileName); return SendFileAsyncCore(response, fileName, 0, null, cancellationToken); } @@ -95,15 +76,8 @@ public static Task SendFileAsync(this HttpResponse response, string fileName, Ca [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required to maintain compatibility")] public static Task SendFileAsync(this HttpResponse response, string fileName, long offset, long? count, CancellationToken cancellationToken = default) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (fileName == null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(fileName); return SendFileAsyncCore(response, fileName, offset, count, cancellationToken); } diff --git a/src/Http/Http.Extensions/src/UriHelper.cs b/src/Http/Http.Extensions/src/UriHelper.cs index a2e68dda6023..6c98c4d4890b 100644 --- a/src/Http/Http.Extensions/src/UriHelper.cs +++ b/src/Http/Http.Extensions/src/UriHelper.cs @@ -56,10 +56,7 @@ public static string BuildAbsolute( QueryString query = new QueryString(), FragmentString fragment = new FragmentString()) { - if (scheme == null) - { - throw new ArgumentNullException(nameof(scheme)); - } + ArgumentNullException.ThrowIfNull(scheme); var hostText = host.ToUriComponent(); var pathBaseText = pathBase.ToUriComponent(); @@ -113,10 +110,7 @@ public static void FromAbsolute( out QueryString query, out FragmentString fragment) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); path = new PathString(); query = new QueryString(); @@ -164,10 +158,7 @@ public static void FromAbsolute( /// The encoded string version of . public static string Encode(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); if (uri.IsAbsoluteUri) { diff --git a/src/Http/Http.Results/src/AcceptedOfT.cs b/src/Http/Http.Results/src/AcceptedOfT.cs index cc3051108d36..3fabf1b9b34c 100644 --- a/src/Http/Http.Results/src/AcceptedOfT.cs +++ b/src/Http/Http.Results/src/AcceptedOfT.cs @@ -40,10 +40,7 @@ internal Accepted(Uri locationUri, TValue? value) Value = value; HttpResultsHelper.ApplyProblemDetailsDefaultsIfNeeded(Value, StatusCode); - if (locationUri == null) - { - throw new ArgumentNullException(nameof(locationUri)); - } + ArgumentNullException.ThrowIfNull(locationUri); if (locationUri.IsAbsoluteUri) { diff --git a/src/Http/Http.Results/src/FileStreamHttpResult.cs b/src/Http/Http.Results/src/FileStreamHttpResult.cs index 4876449991b4..12266995a453 100644 --- a/src/Http/Http.Results/src/FileStreamHttpResult.cs +++ b/src/Http/Http.Results/src/FileStreamHttpResult.cs @@ -59,10 +59,7 @@ internal FileStreamHttpResult( DateTimeOffset? lastModified = null, EntityTagHeaderValue? entityTag = null) { - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream)); - } + ArgumentNullException.ThrowIfNull(fileStream); FileStream = fileStream; if (fileStream.CanSeek) diff --git a/src/Http/Http.Results/src/SignOutHttpResult.cs b/src/Http/Http.Results/src/SignOutHttpResult.cs index 74044c003a7f..572038fd31fd 100644 --- a/src/Http/Http.Results/src/SignOutHttpResult.cs +++ b/src/Http/Http.Results/src/SignOutHttpResult.cs @@ -50,10 +50,7 @@ internal SignOutHttpResult(string authenticationScheme, AuthenticationProperties /// used to perform the sign-out operation. internal SignOutHttpResult(IList authenticationSchemes, AuthenticationProperties? properties) { - if (authenticationSchemes is null) - { - throw new ArgumentNullException(nameof(authenticationSchemes)); - } + ArgumentNullException.ThrowIfNull(authenticationSchemes); AuthenticationSchemes = authenticationSchemes.AsReadOnly(); Properties = properties; diff --git a/src/Http/Http/src/Features/QueryFeature.cs b/src/Http/Http/src/Features/QueryFeature.cs index b8e0035f93a4..040b4592a810 100644 --- a/src/Http/Http/src/Features/QueryFeature.cs +++ b/src/Http/Http/src/Features/QueryFeature.cs @@ -27,10 +27,7 @@ public class QueryFeature : IQueryFeature /// The to use as a backing store. public QueryFeature(IQueryCollection query) { - if (query == null) - { - throw new ArgumentNullException(nameof(query)); - } + ArgumentNullException.ThrowIfNull(query); _parsedValues = query; } @@ -41,10 +38,7 @@ public QueryFeature(IQueryCollection query) /// The to initialize. public QueryFeature(IFeatureCollection features) { - if (features == null) - { - throw new ArgumentNullException(nameof(features)); - } + ArgumentNullException.ThrowIfNull(features); _features.Initalize(features); } diff --git a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs index cc94dd4f793a..ce1074d888c4 100644 --- a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs +++ b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs @@ -23,10 +23,7 @@ public class RequestBodyPipeFeature : IRequestBodyPipeFeature /// public RequestBodyPipeFeature(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _context = context; } diff --git a/src/Http/Http/src/Features/RequestCookiesFeature.cs b/src/Http/Http/src/Features/RequestCookiesFeature.cs index fac74815f328..098169a1b966 100644 --- a/src/Http/Http/src/Features/RequestCookiesFeature.cs +++ b/src/Http/Http/src/Features/RequestCookiesFeature.cs @@ -24,10 +24,7 @@ public class RequestCookiesFeature : IRequestCookiesFeature /// The to use as backing store. public RequestCookiesFeature(IRequestCookieCollection cookies) { - if (cookies == null) - { - throw new ArgumentNullException(nameof(cookies)); - } + ArgumentNullException.ThrowIfNull(cookies); _parsedValues = cookies; } @@ -38,10 +35,7 @@ public RequestCookiesFeature(IRequestCookieCollection cookies) /// The to initialize. public RequestCookiesFeature(IFeatureCollection features) { - if (features == null) - { - throw new ArgumentNullException(nameof(features)); - } + ArgumentNullException.ThrowIfNull(features); _features.Initalize(features); } diff --git a/src/Http/Http/src/FormFile.cs b/src/Http/Http/src/FormFile.cs index ff57e28cde72..bcce6a5986b0 100644 --- a/src/Http/Http/src/FormFile.cs +++ b/src/Http/Http/src/FormFile.cs @@ -83,10 +83,7 @@ public Stream OpenReadStream() /// The stream to copy the file contents to. public void CopyTo(Stream target) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); using (var readStream = OpenReadStream()) { @@ -101,10 +98,7 @@ public void CopyTo(Stream target) /// public async Task CopyToAsync(Stream target, CancellationToken cancellationToken = default(CancellationToken)) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); using (var readStream = OpenReadStream()) { diff --git a/src/Http/Http/src/HeaderDictionary.cs b/src/Http/Http/src/HeaderDictionary.cs index dc399d1ae7b6..7a32f5ce6250 100644 --- a/src/Http/Http/src/HeaderDictionary.cs +++ b/src/Http/Http/src/HeaderDictionary.cs @@ -77,10 +77,7 @@ public StringValues this[string key] } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); ThrowIfReadOnly(); if (value.Count == 0) @@ -199,10 +196,7 @@ public void Add(KeyValuePair item) /// The header values. public void Add(string key, StringValues value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); ThrowIfReadOnly(); EnsureStore(1); Store.Add(key, value); diff --git a/src/Http/Http/src/HttpServiceCollectionExtensions.cs b/src/Http/Http/src/HttpServiceCollectionExtensions.cs index c6053cb38ed8..904df3b6fc90 100644 --- a/src/Http/Http/src/HttpServiceCollectionExtensions.cs +++ b/src/Http/Http/src/HttpServiceCollectionExtensions.cs @@ -18,10 +18,7 @@ public static class HttpServiceCollectionExtensions /// The service collection. public static IServiceCollection AddHttpContextAccessor(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); return services; diff --git a/src/Http/Http/src/Internal/BufferingHelper.cs b/src/Http/Http/src/Internal/BufferingHelper.cs index 307cbc9dc56c..8b407c8d2376 100644 --- a/src/Http/Http/src/Internal/BufferingHelper.cs +++ b/src/Http/Http/src/Internal/BufferingHelper.cs @@ -12,10 +12,7 @@ internal static class BufferingHelper public static HttpRequest EnableRewind(this HttpRequest request, int bufferThreshold = DefaultBufferThreshold, long? bufferLimit = null) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); var body = request.Body; if (!body.CanSeek) @@ -30,14 +27,8 @@ public static HttpRequest EnableRewind(this HttpRequest request, int bufferThres public static MultipartSection EnableRewind(this MultipartSection section, Action registerForDispose, int bufferThreshold = DefaultBufferThreshold, long? bufferLimit = null) { - if (section == null) - { - throw new ArgumentNullException(nameof(section)); - } - if (registerForDispose == null) - { - throw new ArgumentNullException(nameof(registerForDispose)); - } + ArgumentNullException.ThrowIfNull(section); + ArgumentNullException.ThrowIfNull(registerForDispose); var body = section.Body; if (!body.CanSeek) diff --git a/src/Http/Http/src/Internal/DefaultHttpResponse.cs b/src/Http/Http/src/Internal/DefaultHttpResponse.cs index fb3ca0197c77..6961d7a28c7b 100644 --- a/src/Http/Http/src/Internal/DefaultHttpResponse.cs +++ b/src/Http/Http/src/Internal/DefaultHttpResponse.cs @@ -121,20 +121,14 @@ public override PipeWriter BodyWriter public override void OnStarting(Func callback, object state) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); HttpResponseFeature.OnStarting(callback, state); } public override void OnCompleted(Func callback, object state) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); HttpResponseFeature.OnCompleted(callback, state); } diff --git a/src/Http/Http/src/Internal/ReferenceReadStream.cs b/src/Http/Http/src/Internal/ReferenceReadStream.cs index 97f79f6911a6..c925c15ca749 100644 --- a/src/Http/Http/src/Internal/ReferenceReadStream.cs +++ b/src/Http/Http/src/Internal/ReferenceReadStream.cs @@ -17,10 +17,7 @@ internal sealed class ReferenceReadStream : Stream public ReferenceReadStream(Stream inner, long offset, long length) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullException.ThrowIfNull(inner); _inner = inner; _innerOffset = offset; diff --git a/src/Http/Http/src/Internal/RequestCookieCollection.cs b/src/Http/Http/src/Internal/RequestCookieCollection.cs index 8ed1de311c9d..ecc8e772dd03 100644 --- a/src/Http/Http/src/Internal/RequestCookieCollection.cs +++ b/src/Http/Http/src/Internal/RequestCookieCollection.cs @@ -40,10 +40,7 @@ public string? this[string key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (Store == null) { diff --git a/src/Http/Http/src/Internal/ResponseCookies.cs b/src/Http/Http/src/Internal/ResponseCookies.cs index 015699d168ab..9dfe93e7c1cd 100644 --- a/src/Http/Http/src/Internal/ResponseCookies.cs +++ b/src/Http/Http/src/Internal/ResponseCookies.cs @@ -43,10 +43,7 @@ public void Append(string key, string value) /// public void Append(string key, string value, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // SameSite=None cookies must be marked as Secure. if (!options.Secure && options.SameSite == SameSiteMode.None) @@ -70,10 +67,7 @@ public void Append(string key, string value, CookieOptions options) /// public void Append(ReadOnlySpan> keyValuePairs, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // SameSite=None cookies must be marked as Secure. if (!options.Secure && options.SameSite == SameSiteMode.None) @@ -117,10 +111,7 @@ public void Delete(string key) /// public void Delete(string key, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); var encodedKeyPlusEquals = key + "="; var domainHasValue = !string.IsNullOrEmpty(options.Domain); diff --git a/src/Http/Http/src/RequestFormReaderExtensions.cs b/src/Http/Http/src/RequestFormReaderExtensions.cs index a1d573837488..46939bc67d0c 100644 --- a/src/Http/Http/src/RequestFormReaderExtensions.cs +++ b/src/Http/Http/src/RequestFormReaderExtensions.cs @@ -21,14 +21,8 @@ public static class RequestFormReaderExtensions public static Task ReadFormAsync(this HttpRequest request, FormOptions options, CancellationToken cancellationToken = new CancellationToken()) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(options); if (!request.HasFormContentType) { diff --git a/src/Http/Owin/src/OwinEnvironment.cs b/src/Http/Owin/src/OwinEnvironment.cs index 5c9295fc8d08..cc2995a10afe 100644 --- a/src/Http/Owin/src/OwinEnvironment.cs +++ b/src/Http/Owin/src/OwinEnvironment.cs @@ -254,14 +254,8 @@ bool ICollection>.Contains(KeyValuePair>.CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array is null) - { - throw new ArgumentNullException(nameof(array)); - } - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - } + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (arrayIndex + _entries.Count + _context.Items.Count > array.Length) { throw new ArgumentException("Not enough available space in array", nameof(array)); diff --git a/src/Http/Owin/src/OwinExtensions.cs b/src/Http/Owin/src/OwinExtensions.cs index 6df3f0fedbae..cbf4028f5b65 100644 --- a/src/Http/Owin/src/OwinExtensions.cs +++ b/src/Http/Owin/src/OwinExtensions.cs @@ -29,10 +29,7 @@ public static class OwinExtensions /// An action used to create the OWIN pipeline. public static AddMiddleware UseOwin(this IApplicationBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddMiddleware add = middleware => { @@ -75,14 +72,8 @@ public static AddMiddleware UseOwin(this IApplicationBuilder builder) /// The original . public static IApplicationBuilder UseOwin(this IApplicationBuilder builder, Action pipeline) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (pipeline == null) - { - throw new ArgumentNullException(nameof(pipeline)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(pipeline); pipeline(builder.UseOwin()); return builder; @@ -106,10 +97,7 @@ public static IApplicationBuilder UseBuilder(this AddMiddleware app) /// An . public static IApplicationBuilder UseBuilder(this AddMiddleware app, IServiceProvider serviceProvider) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); // Do not set ApplicationBuilder.ApplicationServices to null. May fail later due to missing services but // at least that results in a more useful Exception than a NRE. @@ -184,14 +172,8 @@ public static AddMiddleware UseBuilder(this AddMiddleware app, ActionAn . public static AddMiddleware UseBuilder(this AddMiddleware app, Action pipeline, IServiceProvider serviceProvider) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (pipeline == null) - { - throw new ArgumentNullException(nameof(pipeline)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(pipeline); var builder = app.UseBuilder(serviceProvider); pipeline(builder); diff --git a/src/Http/Routing.Abstractions/src/RouteContext.cs b/src/Http/Routing.Abstractions/src/RouteContext.cs index f11214c0a36e..a8ea97f595c7 100644 --- a/src/Http/Routing.Abstractions/src/RouteContext.cs +++ b/src/Http/Routing.Abstractions/src/RouteContext.cs @@ -45,10 +45,7 @@ public RouteData RouteData } set { - if (value == null) - { - throw new ArgumentNullException(nameof(RouteData)); - } + ArgumentNullException.ThrowIfNull(value); _routeData = value; } diff --git a/src/Http/Routing.Abstractions/src/RouteData.cs b/src/Http/Routing.Abstractions/src/RouteData.cs index 14cd7a329cc4..b9c586b0fa0c 100644 --- a/src/Http/Routing.Abstractions/src/RouteData.cs +++ b/src/Http/Routing.Abstractions/src/RouteData.cs @@ -30,10 +30,7 @@ public RouteData() /// The other instance to copy. public RouteData(RouteData other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); // Perf: Avoid allocating collections unless we need to make a copy. if (other._routers != null) @@ -58,10 +55,7 @@ public RouteData(RouteData other) /// The values. public RouteData(RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); _values = values; } @@ -212,10 +206,7 @@ public RouteDataSnapshot( IList? routers, RouteValueDictionary? values) { - if (routeData == null) - { - throw new ArgumentNullException(nameof(routeData)); - } + ArgumentNullException.ThrowIfNull(routeData); _routeData = routeData; _dataTokens = dataTokens; diff --git a/src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs b/src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs index 03e72ba00276..192bca0e75d8 100644 --- a/src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs +++ b/src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs @@ -20,10 +20,7 @@ public static class RoutingHttpContextExtensions /// The . public static RouteData GetRouteData(this HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var routingFeature = httpContext.Features.Get(); return routingFeature?.RouteData ?? new RouteData(httpContext.Request.RouteValues); @@ -38,15 +35,8 @@ public static RouteData GetRouteData(this HttpContext httpContext) /// The corresponding route value, or null. public static object? GetRouteValue(this HttpContext httpContext, string key) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(key); return httpContext.Features.Get()?.RouteValues[key]; } diff --git a/src/Http/Routing.Abstractions/src/VirtualPathData.cs b/src/Http/Routing.Abstractions/src/VirtualPathData.cs index 4adb0caabc5b..8e61e13601ec 100644 --- a/src/Http/Routing.Abstractions/src/VirtualPathData.cs +++ b/src/Http/Routing.Abstractions/src/VirtualPathData.cs @@ -33,10 +33,7 @@ public VirtualPathData( string virtualPath, RouteValueDictionary dataTokens) { - if (router == null) - { - throw new ArgumentNullException(nameof(router)); - } + ArgumentNullException.ThrowIfNull(router); Router = router; VirtualPath = virtualPath; diff --git a/src/Http/Routing/perf/Microbenchmarks/Matching/TrivialMatcher.cs b/src/Http/Routing/perf/Microbenchmarks/Matching/TrivialMatcher.cs index d051a274c22a..a444510299ab 100644 --- a/src/Http/Routing/perf/Microbenchmarks/Matching/TrivialMatcher.cs +++ b/src/Http/Routing/perf/Microbenchmarks/Matching/TrivialMatcher.cs @@ -22,10 +22,7 @@ public TrivialMatcher(RouteEndpoint endpoint) public sealed override Task MatchAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var path = httpContext.Request.Path.Value; if (string.Equals(_endpoint.RoutePattern.RawText, path, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Http/Routing/src/ConfigureRouteOptions.cs b/src/Http/Routing/src/ConfigureRouteOptions.cs index d4264791717f..b3a3892ceb0c 100644 --- a/src/Http/Routing/src/ConfigureRouteOptions.cs +++ b/src/Http/Routing/src/ConfigureRouteOptions.cs @@ -12,20 +12,14 @@ internal sealed class ConfigureRouteOptions : IConfigureOptions public ConfigureRouteOptions(ICollection dataSources) { - if (dataSources == null) - { - throw new ArgumentNullException(nameof(dataSources)); - } + ArgumentNullException.ThrowIfNull(dataSources); _dataSources = dataSources; } public void Configure(RouteOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.EndpointDataSources = _dataSources; } diff --git a/src/Http/Routing/src/Constraints/BoolRouteConstraint.cs b/src/Http/Routing/src/Constraints/BoolRouteConstraint.cs index 420b20105fb0..e05b02a32392 100644 --- a/src/Http/Routing/src/Constraints/BoolRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/BoolRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/CompositeRouteConstraint.cs b/src/Http/Routing/src/Constraints/CompositeRouteConstraint.cs index 7ae90eca4c7e..cecfdca08e27 100644 --- a/src/Http/Routing/src/Constraints/CompositeRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/CompositeRouteConstraint.cs @@ -17,10 +17,7 @@ public class CompositeRouteConstraint : IRouteConstraint, IParameterLiteralNodeM /// The child constraints that must match for this constraint to match. public CompositeRouteConstraint(IEnumerable constraints) { - if (constraints == null) - { - throw new ArgumentNullException(nameof(constraints)); - } + ArgumentNullException.ThrowIfNull(constraints); Constraints = constraints; } @@ -38,15 +35,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); foreach (var constraint in Constraints) { diff --git a/src/Http/Routing/src/Constraints/DateTimeRouteConstraint.cs b/src/Http/Routing/src/Constraints/DateTimeRouteConstraint.cs index 406607f1d419..a2cbf016cfb8 100644 --- a/src/Http/Routing/src/Constraints/DateTimeRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/DateTimeRouteConstraint.cs @@ -26,15 +26,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/DecimalRouteConstraint.cs b/src/Http/Routing/src/Constraints/DecimalRouteConstraint.cs index 391046151273..0923fa65dac4 100644 --- a/src/Http/Routing/src/Constraints/DecimalRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/DecimalRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/DoubleRouteConstraint.cs b/src/Http/Routing/src/Constraints/DoubleRouteConstraint.cs index 286e219e6882..0032c051e97e 100644 --- a/src/Http/Routing/src/Constraints/DoubleRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/DoubleRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs b/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs index 50d7cebfdb55..c3476a7bdc18 100644 --- a/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/FileNameRouteConstraint.cs @@ -91,15 +91,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var obj) && obj != null) { diff --git a/src/Http/Routing/src/Constraints/FloatRouteConstraint.cs b/src/Http/Routing/src/Constraints/FloatRouteConstraint.cs index 1cab829947e4..bb50909b863f 100644 --- a/src/Http/Routing/src/Constraints/FloatRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/FloatRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/GuidRouteConstraint.cs b/src/Http/Routing/src/Constraints/GuidRouteConstraint.cs index 353440a875e2..17463aedb40b 100644 --- a/src/Http/Routing/src/Constraints/GuidRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/GuidRouteConstraint.cs @@ -22,15 +22,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/HttpMethodRouteConstraint.cs b/src/Http/Routing/src/Constraints/HttpMethodRouteConstraint.cs index dffc6e9d7d82..83d6bf982d86 100644 --- a/src/Http/Routing/src/Constraints/HttpMethodRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/HttpMethodRouteConstraint.cs @@ -19,10 +19,7 @@ public class HttpMethodRouteConstraint : IRouteConstraint /// The allowed HTTP methods. public HttpMethodRouteConstraint(params string[] allowedMethods) { - if (allowedMethods == null) - { - throw new ArgumentNullException(nameof(allowedMethods)); - } + ArgumentNullException.ThrowIfNull(allowedMethods); AllowedMethods = new List(allowedMethods); } @@ -40,24 +37,14 @@ public virtual bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); switch (routeDirection) { case RouteDirection.IncomingRequest: // Only required for constraining incoming requests - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); return AllowedMethods.Contains(httpContext.Request.Method, StringComparer.OrdinalIgnoreCase); diff --git a/src/Http/Routing/src/Constraints/IntRouteConstraint.cs b/src/Http/Routing/src/Constraints/IntRouteConstraint.cs index 163d4f794bdd..f2ab6a06fb9b 100644 --- a/src/Http/Routing/src/Constraints/IntRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/IntRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/LengthRouteConstraint.cs b/src/Http/Routing/src/Constraints/LengthRouteConstraint.cs index 5aea26962331..da5d2490b817 100644 --- a/src/Http/Routing/src/Constraints/LengthRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/LengthRouteConstraint.cs @@ -77,15 +77,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/LongRouteConstraint.cs b/src/Http/Routing/src/Constraints/LongRouteConstraint.cs index f7d5625ffa55..9ffbd6d24574 100644 --- a/src/Http/Routing/src/Constraints/LongRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/LongRouteConstraint.cs @@ -20,15 +20,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/MaxLengthRouteConstraint.cs b/src/Http/Routing/src/Constraints/MaxLengthRouteConstraint.cs index 1d42c443aa03..643ea5082e4f 100644 --- a/src/Http/Routing/src/Constraints/MaxLengthRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/MaxLengthRouteConstraint.cs @@ -40,15 +40,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/MaxRouteConstraint.cs b/src/Http/Routing/src/Constraints/MaxRouteConstraint.cs index 795e273886f7..e4b3e54ee665 100644 --- a/src/Http/Routing/src/Constraints/MaxRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/MaxRouteConstraint.cs @@ -34,15 +34,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/MinLengthRouteConstraint.cs b/src/Http/Routing/src/Constraints/MinLengthRouteConstraint.cs index d3274e4a5f93..3d3393a04d7e 100644 --- a/src/Http/Routing/src/Constraints/MinLengthRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/MinLengthRouteConstraint.cs @@ -40,15 +40,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/MinRouteConstraint.cs b/src/Http/Routing/src/Constraints/MinRouteConstraint.cs index fd2bdbe96d53..43e2e1d2a1aa 100644 --- a/src/Http/Routing/src/Constraints/MinRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/MinRouteConstraint.cs @@ -34,15 +34,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/NonFileNameRouteConstraint.cs b/src/Http/Routing/src/Constraints/NonFileNameRouteConstraint.cs index 375cd3864322..415c89fdeb81 100644 --- a/src/Http/Routing/src/Constraints/NonFileNameRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/NonFileNameRouteConstraint.cs @@ -87,15 +87,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var obj) && obj != null) { diff --git a/src/Http/Routing/src/Constraints/OptionalRouteConstraint.cs b/src/Http/Routing/src/Constraints/OptionalRouteConstraint.cs index 98f976a2a639..2b0d6482c16d 100644 --- a/src/Http/Routing/src/Constraints/OptionalRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/OptionalRouteConstraint.cs @@ -16,10 +16,7 @@ public class OptionalRouteConstraint : IRouteConstraint /// public OptionalRouteConstraint(IRouteConstraint innerConstraint) { - if (innerConstraint == null) - { - throw new ArgumentNullException(nameof(innerConstraint)); - } + ArgumentNullException.ThrowIfNull(innerConstraint); InnerConstraint = innerConstraint; } @@ -37,15 +34,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out _)) { diff --git a/src/Http/Routing/src/Constraints/RangeRouteConstraint.cs b/src/Http/Routing/src/Constraints/RangeRouteConstraint.cs index 576b6b6034cb..d66e9e05cd9a 100644 --- a/src/Http/Routing/src/Constraints/RangeRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/RangeRouteConstraint.cs @@ -48,15 +48,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/RegexRouteConstraint.cs b/src/Http/Routing/src/Constraints/RegexRouteConstraint.cs index 1d7d7e5e6b52..68cf983e9632 100644 --- a/src/Http/Routing/src/Constraints/RegexRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/RegexRouteConstraint.cs @@ -22,10 +22,7 @@ public class RegexRouteConstraint : IRouteConstraint, IParameterLiteralNodeMatch /// A instance to use as a constraint. public RegexRouteConstraint(Regex regex) { - if (regex == null) - { - throw new ArgumentNullException(nameof(regex)); - } + ArgumentNullException.ThrowIfNull(regex); Constraint = regex; } @@ -38,10 +35,7 @@ public RegexRouteConstraint( [StringSyntax(StringSyntaxAttribute.Regex, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)] string regexPattern) { - if (regexPattern == null) - { - throw new ArgumentNullException(nameof(regexPattern)); - } + ArgumentNullException.ThrowIfNull(regexPattern); Constraint = new Regex( regexPattern, @@ -62,15 +56,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var routeValue) && routeValue != null) diff --git a/src/Http/Routing/src/Constraints/RequiredRouteConstraint.cs b/src/Http/Routing/src/Constraints/RequiredRouteConstraint.cs index ee78a95bfc02..9e379dadec0b 100644 --- a/src/Http/Routing/src/Constraints/RequiredRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/RequiredRouteConstraint.cs @@ -23,15 +23,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var value) && value != null) { diff --git a/src/Http/Routing/src/Constraints/StringRouteConstraint.cs b/src/Http/Routing/src/Constraints/StringRouteConstraint.cs index ba25b4733cbb..40b36510ba17 100644 --- a/src/Http/Routing/src/Constraints/StringRouteConstraint.cs +++ b/src/Http/Routing/src/Constraints/StringRouteConstraint.cs @@ -20,10 +20,7 @@ public class StringRouteConstraint : IRouteConstraint, IParameterLiteralNodeMatc /// The constraint value to match. public StringRouteConstraint(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _value = value; } @@ -31,15 +28,8 @@ public StringRouteConstraint(string value) /// public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var routeValue) && routeValue != null) diff --git a/src/Http/Routing/src/DataSourceDependentCache.cs b/src/Http/Routing/src/DataSourceDependentCache.cs index c712b55974d2..98713da723e2 100644 --- a/src/Http/Routing/src/DataSourceDependentCache.cs +++ b/src/Http/Routing/src/DataSourceDependentCache.cs @@ -26,15 +26,8 @@ internal sealed class DataSourceDependentCache : IDisposable where T : class public DataSourceDependentCache(EndpointDataSource dataSource, Func, T> initialize) { - if (dataSource == null) - { - throw new ArgumentNullException(nameof(dataSource)); - } - - if (initialize == null) - { - throw new ArgumentNullException(nameof(initialize)); - } + ArgumentNullException.ThrowIfNull(dataSource); + ArgumentNullException.ThrowIfNull(initialize); _dataSource = dataSource; _initializeCore = initialize; diff --git a/src/Http/Routing/src/DefaultEndpointDataSource.cs b/src/Http/Routing/src/DefaultEndpointDataSource.cs index 940471d91fc0..323d6893277f 100644 --- a/src/Http/Routing/src/DefaultEndpointDataSource.cs +++ b/src/Http/Routing/src/DefaultEndpointDataSource.cs @@ -22,10 +22,7 @@ public sealed class DefaultEndpointDataSource : EndpointDataSource /// The instances that the data source will return. public DefaultEndpointDataSource(params Endpoint[] endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); _endpoints = (Endpoint[])endpoints.Clone(); } @@ -36,10 +33,7 @@ public DefaultEndpointDataSource(params Endpoint[] endpoints) /// The instances that the data source will return. public DefaultEndpointDataSource(IEnumerable endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); _endpoints = new List(endpoints); } diff --git a/src/Http/Routing/src/DefaultInlineConstraintResolver.cs b/src/Http/Routing/src/DefaultInlineConstraintResolver.cs index ad7ba5948ab3..4974ab6b3cfd 100644 --- a/src/Http/Routing/src/DefaultInlineConstraintResolver.cs +++ b/src/Http/Routing/src/DefaultInlineConstraintResolver.cs @@ -24,15 +24,8 @@ public class DefaultInlineConstraintResolver : IInlineConstraintResolver /// The to get service arguments from. public DefaultInlineConstraintResolver(IOptions routeOptions, IServiceProvider serviceProvider) { - if (routeOptions == null) - { - throw new ArgumentNullException(nameof(routeOptions)); - } - - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(routeOptions); + ArgumentNullException.ThrowIfNull(serviceProvider); _inlineConstraintMap = routeOptions.Value.TrimmerSafeConstraintMap; _serviceProvider = serviceProvider; @@ -48,10 +41,7 @@ public DefaultInlineConstraintResolver(IOptions routeOptions, ISer /// public virtual IRouteConstraint? ResolveConstraint(string inlineConstraint) { - if (inlineConstraint == null) - { - throw new ArgumentNullException(nameof(inlineConstraint)); - } + ArgumentNullException.ThrowIfNull(inlineConstraint); // This will return null if the text resolves to a non-IRouteConstraint return ParameterPolicyActivator.ResolveParameterPolicy( diff --git a/src/Http/Routing/src/DefaultLinkGenerator.cs b/src/Http/Routing/src/DefaultLinkGenerator.cs index c8c451069d42..15e9a11a5a52 100644 --- a/src/Http/Routing/src/DefaultLinkGenerator.cs +++ b/src/Http/Routing/src/DefaultLinkGenerator.cs @@ -72,10 +72,7 @@ public DefaultLinkGenerator( FragmentString fragment = default, LinkOptions? options = null) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var endpoints = GetEndpoints(address); if (endpoints.Count == 0) @@ -127,10 +124,7 @@ public DefaultLinkGenerator( FragmentString fragment = default, LinkOptions? options = null) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var endpoints = GetEndpoints(address); if (endpoints.Count == 0) diff --git a/src/Http/Routing/src/DefaultParameterPolicyFactory.cs b/src/Http/Routing/src/DefaultParameterPolicyFactory.cs index 1b76e85c5405..8f7cf63f24a9 100644 --- a/src/Http/Routing/src/DefaultParameterPolicyFactory.cs +++ b/src/Http/Routing/src/DefaultParameterPolicyFactory.cs @@ -22,10 +22,7 @@ public DefaultParameterPolicyFactory( public override IParameterPolicy Create(RoutePatternParameterPart? parameter, IParameterPolicy parameterPolicy) { - if (parameterPolicy == null) - { - throw new ArgumentNullException(nameof(parameterPolicy)); - } + ArgumentNullException.ThrowIfNull(parameterPolicy); if (parameterPolicy is IRouteConstraint routeConstraint) { @@ -37,10 +34,7 @@ public override IParameterPolicy Create(RoutePatternParameterPart? parameter, IP public override IParameterPolicy Create(RoutePatternParameterPart? parameter, string inlineText) { - if (inlineText == null) - { - throw new ArgumentNullException(nameof(inlineText)); - } + ArgumentNullException.ThrowIfNull(inlineText); var parameterPolicy = ParameterPolicyActivator.ResolveParameterPolicy( _options.TrimmerSafeConstraintMap, diff --git a/src/Http/Routing/src/DependencyInjection/RoutingServiceCollectionExtensions.cs b/src/Http/Routing/src/DependencyInjection/RoutingServiceCollectionExtensions.cs index 8e2a0f618793..6c912748bca5 100644 --- a/src/Http/Routing/src/DependencyInjection/RoutingServiceCollectionExtensions.cs +++ b/src/Http/Routing/src/DependencyInjection/RoutingServiceCollectionExtensions.cs @@ -27,10 +27,7 @@ public static class RoutingServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddRouting(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddTransient(); services.TryAddTransient(); @@ -114,15 +111,8 @@ public static IServiceCollection AddRouting( this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.AddRouting(); diff --git a/src/Http/Routing/src/EndpointGroupNameAttribute.cs b/src/Http/Routing/src/EndpointGroupNameAttribute.cs index d0c73b56aaaa..9bf1d9003e29 100644 --- a/src/Http/Routing/src/EndpointGroupNameAttribute.cs +++ b/src/Http/Routing/src/EndpointGroupNameAttribute.cs @@ -15,10 +15,7 @@ public sealed class EndpointGroupNameAttribute : Attribute, IEndpointGroupNameMe /// The endpoint group name. public EndpointGroupNameAttribute(string endpointGroupName) { - if (endpointGroupName == null) - { - throw new ArgumentNullException(nameof(endpointGroupName)); - } + ArgumentNullException.ThrowIfNull(endpointGroupName); EndpointGroupName = endpointGroupName; } diff --git a/src/Http/Routing/src/EndpointNameAddressScheme.cs b/src/Http/Routing/src/EndpointNameAddressScheme.cs index 1bf2b769ec80..d8b6029a7f17 100644 --- a/src/Http/Routing/src/EndpointNameAddressScheme.cs +++ b/src/Http/Routing/src/EndpointNameAddressScheme.cs @@ -21,10 +21,7 @@ public EndpointNameAddressScheme(EndpointDataSource dataSource) public IEnumerable FindEndpoints(string address) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); // Capture the current value of the cache var entries = Entries; diff --git a/src/Http/Routing/src/EndpointNameAttribute.cs b/src/Http/Routing/src/EndpointNameAttribute.cs index 9ebcf0a65241..eda3e902c8fa 100644 --- a/src/Http/Routing/src/EndpointNameAttribute.cs +++ b/src/Http/Routing/src/EndpointNameAttribute.cs @@ -21,10 +21,7 @@ public sealed class EndpointNameAttribute : Attribute, IEndpointNameMetadata /// The endpoint name. public EndpointNameAttribute(string endpointName) { - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(endpointName); EndpointName = endpointName; } diff --git a/src/Http/Routing/src/EndpointNameMetadata.cs b/src/Http/Routing/src/EndpointNameMetadata.cs index 2145f3d22c29..b49ec72d3522 100644 --- a/src/Http/Routing/src/EndpointNameMetadata.cs +++ b/src/Http/Routing/src/EndpointNameMetadata.cs @@ -20,10 +20,7 @@ public class EndpointNameMetadata : IEndpointNameMetadata /// The endpoint name. public EndpointNameMetadata(string endpointName) { - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(endpointName); EndpointName = endpointName; } diff --git a/src/Http/Routing/src/EndpointRoutingMiddleware.cs b/src/Http/Routing/src/EndpointRoutingMiddleware.cs index fe336e869c95..709936791705 100644 --- a/src/Http/Routing/src/EndpointRoutingMiddleware.cs +++ b/src/Http/Routing/src/EndpointRoutingMiddleware.cs @@ -30,10 +30,7 @@ public EndpointRoutingMiddleware( DiagnosticListener diagnosticListener, RequestDelegate next) { - if (endpointRouteBuilder == null) - { - throw new ArgumentNullException(nameof(endpointRouteBuilder)); - } + ArgumentNullException.ThrowIfNull(endpointRouteBuilder); _matcherFactory = matcherFactory ?? throw new ArgumentNullException(nameof(matcherFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); diff --git a/src/Http/Routing/src/HostAttribute.cs b/src/Http/Routing/src/HostAttribute.cs index 5bbc518431df..4e75fc482179 100644 --- a/src/Http/Routing/src/HostAttribute.cs +++ b/src/Http/Routing/src/HostAttribute.cs @@ -22,10 +22,7 @@ public sealed class HostAttribute : Attribute, IHostMetadata /// public HostAttribute(string host) : this(new[] { host }) { - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } + ArgumentNullException.ThrowIfNull(host); } /// @@ -38,10 +35,7 @@ public HostAttribute(string host) : this(new[] { host }) /// public HostAttribute(params string[] hosts) { - if (hosts == null) - { - throw new ArgumentNullException(nameof(hosts)); - } + ArgumentNullException.ThrowIfNull(hosts); Hosts = hosts.ToArray(); } diff --git a/src/Http/Routing/src/HttpMethodMetadata.cs b/src/Http/Routing/src/HttpMethodMetadata.cs index 221529b9f28e..1d8450b21dd4 100644 --- a/src/Http/Routing/src/HttpMethodMetadata.cs +++ b/src/Http/Routing/src/HttpMethodMetadata.cs @@ -35,10 +35,7 @@ public HttpMethodMetadata(IEnumerable httpMethods) /// A value indicating whether routing accepts CORS preflight requests. public HttpMethodMetadata(IEnumerable httpMethods, bool acceptCorsPreflight) { - if (httpMethods == null) - { - throw new ArgumentNullException(nameof(httpMethods)); - } + ArgumentNullException.ThrowIfNull(httpMethods); HttpMethods = httpMethods.Select(GetCanonicalizedValue).ToArray(); AcceptCorsPreflight = acceptCorsPreflight; diff --git a/src/Http/Routing/src/InlineRouteParameterParser.cs b/src/Http/Routing/src/InlineRouteParameterParser.cs index ba5ed0a061d8..5dacbbd6f204 100644 --- a/src/Http/Routing/src/InlineRouteParameterParser.cs +++ b/src/Http/Routing/src/InlineRouteParameterParser.cs @@ -17,10 +17,7 @@ public static class InlineRouteParameterParser /// A instance. public static TemplatePart ParseRouteParameter(string routeParameter) { - if (routeParameter == null) - { - throw new ArgumentNullException(nameof(routeParameter)); - } + ArgumentNullException.ThrowIfNull(routeParameter); if (routeParameter.Length == 0) { diff --git a/src/Http/Routing/src/LinkGeneratorEndpointNameAddressExtensions.cs b/src/Http/Routing/src/LinkGeneratorEndpointNameAddressExtensions.cs index 3ede96df1e54..c875e522dcf4 100644 --- a/src/Http/Routing/src/LinkGeneratorEndpointNameAddressExtensions.cs +++ b/src/Http/Routing/src/LinkGeneratorEndpointNameAddressExtensions.cs @@ -37,20 +37,9 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetPathByAddress( httpContext, @@ -88,20 +77,9 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetPathByAddress( httpContext, @@ -135,15 +113,8 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetPathByAddress(endpointName, new RouteValueDictionary(values), pathBase, fragment, options); } @@ -170,15 +141,8 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetPathByAddress(endpointName, values ?? new(), pathBase, fragment, options); } @@ -226,20 +190,9 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetUriByAddress( httpContext, @@ -296,20 +249,9 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(endpointName); return generator.GetUriByAddress( httpContext, @@ -360,15 +302,8 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(endpointName); if (string.IsNullOrEmpty(scheme)) { @@ -420,15 +355,8 @@ public static class LinkGeneratorEndpointNameAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(endpointName); if (string.IsNullOrEmpty(scheme)) { diff --git a/src/Http/Routing/src/LinkGeneratorRouteValuesAddressExtensions.cs b/src/Http/Routing/src/LinkGeneratorRouteValuesAddressExtensions.cs index c83ab68d1e4e..4a26f2036a86 100644 --- a/src/Http/Routing/src/LinkGeneratorRouteValuesAddressExtensions.cs +++ b/src/Http/Routing/src/LinkGeneratorRouteValuesAddressExtensions.cs @@ -37,15 +37,8 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, routeName, new(values)); return generator.GetPathByAddress( @@ -84,15 +77,8 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, routeName, values); return generator.GetPathByAddress( @@ -127,10 +113,7 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } + ArgumentNullException.ThrowIfNull(generator); var address = CreateAddress(httpContext: null, routeName, new(values)); return generator.GetPathByAddress(address, address.ExplicitValues, pathBase, fragment, options); @@ -158,10 +141,7 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } + ArgumentNullException.ThrowIfNull(generator); var address = CreateAddress(httpContext: null, routeName, values); return generator.GetPathByAddress(address, address.ExplicitValues, pathBase, fragment, options); @@ -210,15 +190,8 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, routeName, new(values)); return generator.GetUriByAddress( @@ -276,15 +249,8 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, routeName, values); return generator.GetUriByAddress( @@ -336,10 +302,7 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } + ArgumentNullException.ThrowIfNull(generator); var address = CreateAddress(httpContext: null, routeName, new(values)); return generator.GetUriByAddress(address, address.ExplicitValues, scheme, host, pathBase, fragment, options); @@ -382,10 +345,7 @@ public static class LinkGeneratorRouteValuesAddressExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } + ArgumentNullException.ThrowIfNull(generator); var address = CreateAddress(httpContext: null, routeName, values); return generator.GetUriByAddress(address, address.ExplicitValues, scheme, host, pathBase, fragment, options); diff --git a/src/Http/Routing/src/LinkParserEndpointNameAddressExtensions.cs b/src/Http/Routing/src/LinkParserEndpointNameAddressExtensions.cs index ae2945febe78..a589b2a8a461 100644 --- a/src/Http/Routing/src/LinkParserEndpointNameAddressExtensions.cs +++ b/src/Http/Routing/src/LinkParserEndpointNameAddressExtensions.cs @@ -37,15 +37,8 @@ public static class LinkParserEndpointNameAddressExtensions string endpointName, PathString path) { - if (parser == null) - { - throw new ArgumentNullException(nameof(parser)); - } - - if (endpointName == null) - { - throw new ArgumentNullException(nameof(endpointName)); - } + ArgumentNullException.ThrowIfNull(parser); + ArgumentNullException.ThrowIfNull(endpointName); return parser.ParsePathByAddress(endpointName, path); } diff --git a/src/Http/Routing/src/Matching/AcceptsMatcherPolicy.cs b/src/Http/Routing/src/Matching/AcceptsMatcherPolicy.cs index 87931a0306f0..d5ad6779d4c1 100644 --- a/src/Http/Routing/src/Matching/AcceptsMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/AcceptsMatcherPolicy.cs @@ -21,10 +21,7 @@ internal sealed class AcceptsMatcherPolicy : MatcherPolicy, IEndpointComparerPol bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); if (ContainsDynamicEndpoints(endpoints)) { @@ -36,10 +33,7 @@ bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList endpoints) bool IEndpointSelectorPolicy.AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // When the node contains dynamic endpoints we can't make any assumptions. return ContainsDynamicEndpoints(endpoints); @@ -52,15 +46,8 @@ private static bool AppliesToEndpointsCore(IReadOnlyList endpoints) public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); // We want to return a 415 if we eliminated ALL of the currently valid endpoints due to content type // mismatch. @@ -150,10 +137,7 @@ public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) public IReadOnlyList GetEdges(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // The algorithm here is designed to be preserve the order of the endpoints // while also being relatively simple. Preserving order is important. @@ -270,10 +254,7 @@ private static Endpoint CreateRejectionEndpoint() public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList edges) { - if (edges == null) - { - throw new ArgumentNullException(nameof(edges)); - } + ArgumentNullException.ThrowIfNull(edges); // Since our 'edges' can have wildcards, we do a sort based on how wildcard-ey they // are then then execute them in linear order. diff --git a/src/Http/Routing/src/Matching/CandidateSet.cs b/src/Http/Routing/src/Matching/CandidateSet.cs index b8ec1264983b..77b84b671afe 100644 --- a/src/Http/Routing/src/Matching/CandidateSet.cs +++ b/src/Http/Routing/src/Matching/CandidateSet.cs @@ -34,20 +34,9 @@ public sealed class CandidateSet /// The list of endpoint scores. . public CandidateSet(Endpoint[] endpoints, RouteValueDictionary[] values, int[] scores) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - - if (scores == null) - { - throw new ArgumentNullException(nameof(scores)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(values); + ArgumentNullException.ThrowIfNull(scores); if (endpoints.Length != values.Length || endpoints.Length != scores.Length) { diff --git a/src/Http/Routing/src/Matching/DefaultEndpointSelector.cs b/src/Http/Routing/src/Matching/DefaultEndpointSelector.cs index b9177dfc8cd7..1c51cb68b03f 100644 --- a/src/Http/Routing/src/Matching/DefaultEndpointSelector.cs +++ b/src/Http/Routing/src/Matching/DefaultEndpointSelector.cs @@ -12,15 +12,8 @@ public override Task SelectAsync( HttpContext httpContext, CandidateSet candidateSet) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidateSet == null) - { - throw new ArgumentNullException(nameof(candidateSet)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidateSet); Select(httpContext, candidateSet.Candidates); return Task.CompletedTask; diff --git a/src/Http/Routing/src/Matching/DfaMatcher.cs b/src/Http/Routing/src/Matching/DfaMatcher.cs index bc9cbcb125f3..2e4ce0ef580a 100644 --- a/src/Http/Routing/src/Matching/DfaMatcher.cs +++ b/src/Http/Routing/src/Matching/DfaMatcher.cs @@ -28,10 +28,7 @@ public DfaMatcher(ILogger logger, EndpointSelector selector, DfaStat [SkipLocalsInit] public sealed override Task MatchAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); // All of the logging we do here is at level debug, so we can get away with doing a single check. var log = _logger.IsEnabled(LogLevel.Debug); diff --git a/src/Http/Routing/src/Matching/DfaMatcherFactory.cs b/src/Http/Routing/src/Matching/DfaMatcherFactory.cs index a544cdd5787a..903f18324e4f 100644 --- a/src/Http/Routing/src/Matching/DfaMatcherFactory.cs +++ b/src/Http/Routing/src/Matching/DfaMatcherFactory.cs @@ -13,20 +13,14 @@ internal sealed class DfaMatcherFactory : MatcherFactory // of DfaMatcherBuilder. public DfaMatcherFactory(IServiceProvider services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); _services = services; } public override Matcher CreateMatcher(EndpointDataSource dataSource) { - if (dataSource == null) - { - throw new ArgumentNullException(nameof(dataSource)); - } + ArgumentNullException.ThrowIfNull(dataSource); // Creates a tracking entry in DI to stop listening for change events // when the services are disposed. diff --git a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs index f14824564439..4ea5d01d2609 100644 --- a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs +++ b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs @@ -23,10 +23,7 @@ public sealed class EndpointMetadataComparer : IComparer // using IServiceProvider to break the cycle. internal EndpointMetadataComparer(IServiceProvider services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); _services = services; } @@ -50,15 +47,8 @@ private IComparer[] Comparers int IComparer.Compare(Endpoint? x, Endpoint? y) { - if (x == null) - { - throw new ArgumentNullException(nameof(x)); - } - - if (y == null) - { - throw new ArgumentNullException(nameof(y)); - } + ArgumentNullException.ThrowIfNull(x); + ArgumentNullException.ThrowIfNull(y); var comparers = Comparers; for (var i = 0; i < comparers.Length; i++) @@ -103,15 +93,8 @@ public abstract class EndpointMetadataComparer : IComparer /// public int Compare(Endpoint? x, Endpoint? y) { - if (x == null) - { - throw new ArgumentNullException(nameof(x)); - } - - if (y == null) - { - throw new ArgumentNullException(nameof(y)); - } + ArgumentNullException.ThrowIfNull(x); + ArgumentNullException.ThrowIfNull(y); return CompareMetadata(GetMetadata(x), GetMetadata(y)); } diff --git a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs index 77da6e222652..8ec928d6ae83 100644 --- a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs @@ -25,10 +25,7 @@ public sealed class HostMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); return !ContainsDynamicEndpoints(endpoints) && AppliesToEndpointsCore(endpoints); } @@ -73,15 +70,8 @@ private static bool AppliesToEndpointsCore(IReadOnlyList endpoints) /// public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); for (var i = 0; i < candidates.Count; i++) { @@ -193,10 +183,7 @@ private static EdgeKey CreateEdgeKey(string host) /// public IReadOnlyList GetEdges(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // The algorithm here is designed to be preserve the order of the endpoints // while also being relatively simple. Preserving order is important. @@ -278,10 +265,7 @@ public IReadOnlyList GetEdges(IReadOnlyList endpoints) /// public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList edges) { - if (edges == null) - { - throw new ArgumentNullException(nameof(edges)); - } + ArgumentNullException.ThrowIfNull(edges); // Since our 'edges' can have wildcards, we do a sort based on how wildcard-ey they // are then then execute them in linear order. diff --git a/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs b/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs index cea2791414da..60ca53afa142 100644 --- a/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs @@ -38,10 +38,7 @@ public sealed class HttpMethodMatcherPolicy : MatcherPolicy, IEndpointComparerPo bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); if (ContainsDynamicEndpoints(endpoints)) { @@ -53,10 +50,7 @@ bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList endpoints) bool IEndpointSelectorPolicy.AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // When the node contains dynamic endpoints we can't make any assumptions. return ContainsDynamicEndpoints(endpoints); @@ -83,15 +77,8 @@ private static bool AppliesToEndpointsCore(IReadOnlyList endpoints) /// public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); // Returning a 405 here requires us to return keep track of all 'seen' HTTP methods. We allocate to // keep track of this because we either need to keep track of the HTTP methods or keep track of the diff --git a/src/Http/Routing/src/Matching/MatcherPolicy.cs b/src/Http/Routing/src/Matching/MatcherPolicy.cs index 32a4d9ea2d58..ea9bd79818e3 100644 --- a/src/Http/Routing/src/Matching/MatcherPolicy.cs +++ b/src/Http/Routing/src/Matching/MatcherPolicy.cs @@ -46,10 +46,7 @@ public abstract class MatcherPolicy /// protected static bool ContainsDynamicEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); for (var i = 0; i < endpoints.Count; i++) { diff --git a/src/Http/Routing/src/ParameterPolicyActivator.cs b/src/Http/Routing/src/ParameterPolicyActivator.cs index 22edfc783b65..ca5b77261b57 100644 --- a/src/Http/Routing/src/ParameterPolicyActivator.cs +++ b/src/Http/Routing/src/ParameterPolicyActivator.cs @@ -23,15 +23,8 @@ public static T ResolveParameterPolicy( // IServiceProvider could be null // DefaultInlineConstraintResolver can be created without an IServiceProvider and then call this method - if (inlineParameterPolicyMap == null) - { - throw new ArgumentNullException(nameof(inlineParameterPolicyMap)); - } - - if (inlineParameterPolicy == null) - { - throw new ArgumentNullException(nameof(inlineParameterPolicy)); - } + ArgumentNullException.ThrowIfNull(inlineParameterPolicyMap); + ArgumentNullException.ThrowIfNull(inlineParameterPolicy); string argumentString; var indexOfFirstOpenParens = inlineParameterPolicy.IndexOf('('); diff --git a/src/Http/Routing/src/ParameterPolicyFactory.cs b/src/Http/Routing/src/ParameterPolicyFactory.cs index f98d1399a266..13c46a5fd20c 100644 --- a/src/Http/Routing/src/ParameterPolicyFactory.cs +++ b/src/Http/Routing/src/ParameterPolicyFactory.cs @@ -35,10 +35,7 @@ public abstract class ParameterPolicyFactory /// The for the parameter. public IParameterPolicy Create(RoutePatternParameterPart? parameter, RoutePatternParameterPolicyReference reference) { - if (reference == null) - { - throw new ArgumentNullException(nameof(reference)); - } + ArgumentNullException.ThrowIfNull(reference); Debug.Assert(reference.ParameterPolicy != null || reference.Content != null); diff --git a/src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs b/src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs index 461af9e90ff6..ae65ee50e8e4 100644 --- a/src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs +++ b/src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs @@ -13,10 +13,7 @@ internal sealed class DefaultRoutePatternTransformer : RoutePatternTransformer public DefaultRoutePatternTransformer(ParameterPolicyFactory policyFactory) { - if (policyFactory == null) - { - throw new ArgumentNullException(nameof(policyFactory)); - } + ArgumentNullException.ThrowIfNull(policyFactory); _policyFactory = policyFactory; } @@ -25,20 +22,14 @@ public DefaultRoutePatternTransformer(ParameterPolicyFactory policyFactory) "Consider using a different overload to avoid this issue.")] public override RoutePattern SubstituteRequiredValues(RoutePattern original, object requiredValues) { - if (original == null) - { - throw new ArgumentNullException(nameof(original)); - } + ArgumentNullException.ThrowIfNull(original); return SubstituteRequiredValues(original, new RouteValueDictionary(requiredValues)); } public override RoutePattern SubstituteRequiredValues(RoutePattern original, RouteValueDictionary requiredValues) { - if (original is null) - { - throw new ArgumentNullException(nameof(original)); - } + ArgumentNullException.ThrowIfNull(original); // Process each required value in sequence. Bail if we find any rejection criteria. The goal // of rejection is to avoid creating RoutePattern instances that can't *ever* match. diff --git a/src/Http/Routing/src/Patterns/RouteParameterParser.cs b/src/Http/Routing/src/Patterns/RouteParameterParser.cs index 723dba5146c8..49a61e64196d 100644 --- a/src/Http/Routing/src/Patterns/RouteParameterParser.cs +++ b/src/Http/Routing/src/Patterns/RouteParameterParser.cs @@ -11,10 +11,7 @@ internal static class RouteParameterParser // The factoring between this class and RoutePatternParser is due to legacy. public static RoutePatternParameterPart ParseRouteParameter(string parameter) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } + ArgumentNullException.ThrowIfNull(parameter); if (parameter.Length == 0) { diff --git a/src/Http/Routing/src/Patterns/RoutePattern.cs b/src/Http/Routing/src/Patterns/RoutePattern.cs index aaf7d13aa26b..a4018b432baf 100644 --- a/src/Http/Routing/src/Patterns/RoutePattern.cs +++ b/src/Http/Routing/src/Patterns/RoutePattern.cs @@ -132,10 +132,7 @@ internal RoutePattern( /// The matching parameter or null if no parameter matches the given name. public RoutePatternParameterPart? GetParameter(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var parameters = Parameters; // Read interface .Count once rather than per iteration diff --git a/src/Http/Routing/src/Patterns/RoutePatternException.cs b/src/Http/Routing/src/Patterns/RoutePatternException.cs index 01f99f2cb3cd..59db1d2710c6 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternException.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternException.cs @@ -26,15 +26,8 @@ private RoutePatternException(SerializationInfo info, StreamingContext context) public RoutePatternException([StringSyntax("Route")] string pattern, string message) : base(message) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } - - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(message); Pattern = pattern; } diff --git a/src/Http/Routing/src/Patterns/RoutePatternFactory.cs b/src/Http/Routing/src/Patterns/RoutePatternFactory.cs index d3d6c13748cc..e88f09aba12e 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternFactory.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternFactory.cs @@ -29,10 +29,7 @@ public static class RoutePatternFactory /// The . public static RoutePattern Parse([StringSyntax("Route")] string pattern) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); return RoutePatternParser.Parse(pattern); } @@ -57,10 +54,7 @@ public static RoutePattern Parse([StringSyntax("Route")] string pattern) [RequiresUnreferencedCode(RouteValueDictionaryTrimmerWarning.Warning)] public static RoutePattern Parse([StringSyntax("Route")] string pattern, object? defaults, object? parameterPolicies) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, Wrap(defaults), Wrap(parameterPolicies), requiredValues: null, original.PathSegments); @@ -85,10 +79,7 @@ public static RoutePattern Parse([StringSyntax("Route")] string pattern, object? /// The . public static RoutePattern Parse([StringSyntax("Route")] string pattern, RouteValueDictionary? defaults, RouteValueDictionary? parameterPolicies) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, defaults, parameterPolicies, requiredValues: null, original.PathSegments); @@ -117,10 +108,7 @@ public static RoutePattern Parse([StringSyntax("Route")] string pattern, RouteVa [RequiresUnreferencedCode(RouteValueDictionaryTrimmerWarning.Warning)] public static RoutePattern Parse([StringSyntax("Route")] string pattern, object? defaults, object? parameterPolicies, object? requiredValues) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, Wrap(defaults), Wrap(parameterPolicies), Wrap(requiredValues), original.PathSegments); @@ -148,10 +136,7 @@ public static RoutePattern Parse([StringSyntax("Route")] string pattern, object? /// The . public static RoutePattern Parse([StringSyntax("Route")] string pattern, RouteValueDictionary? defaults, RouteValueDictionary? parameterPolicies, RouteValueDictionary? requiredValues) { - if (pattern is null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); var original = RoutePatternParser.Parse(pattern); return PatternCore(original.RawText, defaults, parameterPolicies, requiredValues, original.PathSegments); @@ -164,10 +149,7 @@ public static RoutePattern Parse([StringSyntax("Route")] string pattern, RouteVa /// The . public static RoutePattern Pattern(IEnumerable segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, null, null, null, segments); } @@ -180,10 +162,7 @@ public static RoutePattern Pattern(IEnumerable segments /// The . public static RoutePattern Pattern(string? rawText, IEnumerable segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, null, null, null, segments); } @@ -211,10 +190,7 @@ public static RoutePattern Pattern( object? parameterPolicies, IEnumerable segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } @@ -241,10 +217,7 @@ public static RoutePattern Pattern( RouteValueDictionary? parameterPolicies, IEnumerable segments) { - if (segments is null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, defaults, parameterPolicies, requiredValues: null, segments); } @@ -274,10 +247,7 @@ public static RoutePattern Pattern( object? parameterPolicies, IEnumerable segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } @@ -306,10 +276,7 @@ public static RoutePattern Pattern( RouteValueDictionary? parameterPolicies, IEnumerable segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, defaults, parameterPolicies, requiredValues: null, segments); } @@ -321,10 +288,7 @@ public static RoutePattern Pattern( /// The . public static RoutePattern Pattern(params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, null, null, requiredValues: null, segments); } @@ -337,10 +301,7 @@ public static RoutePattern Pattern(params RoutePatternPathSegment[] segments) /// The . public static RoutePattern Pattern(string rawText, params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, null, null, requiredValues: null, segments); } @@ -368,10 +329,7 @@ public static RoutePattern Pattern( object? parameterPolicies, params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } @@ -398,10 +356,7 @@ public static RoutePattern Pattern( RouteValueDictionary? parameterPolicies, params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(null, defaults, parameterPolicies, requiredValues: null, segments); } @@ -431,10 +386,7 @@ public static RoutePattern Pattern( object? parameterPolicies, params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, new RouteValueDictionary(defaults), new RouteValueDictionary(parameterPolicies), requiredValues: null, segments); } @@ -463,10 +415,7 @@ public static RoutePattern Pattern( RouteValueDictionary? parameterPolicies, params RoutePatternPathSegment[] segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); return PatternCore(rawText, defaults, parameterPolicies, requiredValues: null, segments); } @@ -719,10 +668,7 @@ RoutePatternPart VisitPart(RoutePatternPart part) /// The . public static RoutePatternPathSegment Segment(IEnumerable parts) { - if (parts == null) - { - throw new ArgumentNullException(nameof(parts)); - } + ArgumentNullException.ThrowIfNull(parts); return SegmentCore(parts.ToArray()); } @@ -735,10 +681,7 @@ public static RoutePatternPathSegment Segment(IEnumerable part /// The . public static RoutePatternPathSegment Segment(params RoutePatternPart[] parts) { - if (parts == null) - { - throw new ArgumentNullException(nameof(parts)); - } + ArgumentNullException.ThrowIfNull(parts); return SegmentCore((RoutePatternPart[])parts.Clone()); } @@ -910,10 +853,7 @@ public static RoutePatternParameterPart ParameterPart( throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue); } - if (parameterPolicies == null) - { - throw new ArgumentNullException(nameof(parameterPolicies)); - } + ArgumentNullException.ThrowIfNull(parameterPolicies); return ParameterPartCore( parameterName: parameterName, @@ -952,10 +892,7 @@ public static RoutePatternParameterPart ParameterPart( throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue); } - if (parameterPolicies == null) - { - throw new ArgumentNullException(nameof(parameterPolicies)); - } + ArgumentNullException.ThrowIfNull(parameterPolicies); return ParameterPartCore( parameterName: parameterName, @@ -1025,10 +962,7 @@ public static RoutePatternParameterPolicyReference Constraint(object constraint) /// The . public static RoutePatternParameterPolicyReference Constraint(IRouteConstraint constraint) { - if (constraint == null) - { - throw new ArgumentNullException(nameof(constraint)); - } + ArgumentNullException.ThrowIfNull(constraint); return ParameterPolicyCore(constraint); } @@ -1059,10 +993,7 @@ public static RoutePatternParameterPolicyReference Constraint(string constraint) /// The . public static RoutePatternParameterPolicyReference ParameterPolicy(IParameterPolicy parameterPolicy) { - if (parameterPolicy == null) - { - throw new ArgumentNullException(nameof(parameterPolicy)); - } + ArgumentNullException.ThrowIfNull(parameterPolicy); return ParameterPolicyCore(parameterPolicy); } diff --git a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs index 27844a4ccc4e..99332e3d1ed6 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternMatcher.cs @@ -20,10 +20,7 @@ public RoutePatternMatcher( RoutePattern pattern, RouteValueDictionary defaults) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); RoutePattern = pattern; Defaults = defaults ?? new RouteValueDictionary(); @@ -61,10 +58,7 @@ public RoutePatternMatcher( public bool TryMatch(PathString path, RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); var i = 0; var pathTokenizer = new PathTokenizer(path); diff --git a/src/Http/Routing/src/Patterns/RoutePatternParser.cs b/src/Http/Routing/src/Patterns/RoutePatternParser.cs index 8781147a4f63..5fa61727f3b2 100644 --- a/src/Http/Routing/src/Patterns/RoutePatternParser.cs +++ b/src/Http/Routing/src/Patterns/RoutePatternParser.cs @@ -20,10 +20,7 @@ internal static class RoutePatternParser public static RoutePattern Parse(string pattern) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); var trimmedPattern = TrimPrefix(pattern); diff --git a/src/Http/Routing/src/Route.cs b/src/Http/Routing/src/Route.cs index fbd8bc0f466e..d620ba3d2d38 100644 --- a/src/Http/Routing/src/Route.cs +++ b/src/Http/Routing/src/Route.cs @@ -78,10 +78,7 @@ public Route( constraints, dataTokens) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); _target = target; } diff --git a/src/Http/Routing/src/RouteBase.cs b/src/Http/Routing/src/RouteBase.cs index e1d4aa34cc47..d52bdd9a3de9 100644 --- a/src/Http/Routing/src/RouteBase.cs +++ b/src/Http/Routing/src/RouteBase.cs @@ -39,10 +39,7 @@ public RouteBase( IDictionary? constraints, RouteValueDictionary? dataTokens) { - if (constraintResolver == null) - { - throw new ArgumentNullException(nameof(constraintResolver)); - } + ArgumentNullException.ThrowIfNull(constraintResolver); template = template ?? string.Empty; Name = name; @@ -108,10 +105,7 @@ public RouteBase( /// public virtual Task RouteAsync(RouteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); EnsureMatcher(); EnsureLoggers(context.HttpContext); diff --git a/src/Http/Routing/src/RouteBuilder.cs b/src/Http/Routing/src/RouteBuilder.cs index 9efc025f761c..372dd43d4cf3 100644 --- a/src/Http/Routing/src/RouteBuilder.cs +++ b/src/Http/Routing/src/RouteBuilder.cs @@ -30,10 +30,7 @@ public RouteBuilder(IApplicationBuilder applicationBuilder) /// The default used if a new route is added without a handler. public RouteBuilder(IApplicationBuilder applicationBuilder, IRouter? defaultHandler) { - if (applicationBuilder == null) - { - throw new ArgumentNullException(nameof(applicationBuilder)); - } + ArgumentNullException.ThrowIfNull(applicationBuilder); if (applicationBuilder.ApplicationServices.GetService(typeof(RoutingMarkerService)) == null) { diff --git a/src/Http/Routing/src/RouteCollection.cs b/src/Http/Routing/src/RouteCollection.cs index f21011af9df6..21a6d509f4bb 100644 --- a/src/Http/Routing/src/RouteCollection.cs +++ b/src/Http/Routing/src/RouteCollection.cs @@ -43,10 +43,7 @@ public int Count /// public void Add(IRouter router) { - if (router == null) - { - throw new ArgumentNullException(nameof(router)); - } + ArgumentNullException.ThrowIfNull(router); var namedRouter = router as INamedRouter; if (namedRouter != null) diff --git a/src/Http/Routing/src/RouteConstraintBuilder.cs b/src/Http/Routing/src/RouteConstraintBuilder.cs index b8f536618c71..af61ef979bc7 100644 --- a/src/Http/Routing/src/RouteConstraintBuilder.cs +++ b/src/Http/Routing/src/RouteConstraintBuilder.cs @@ -28,15 +28,8 @@ public RouteConstraintBuilder( IInlineConstraintResolver inlineConstraintResolver, string displayName) { - if (inlineConstraintResolver == null) - { - throw new ArgumentNullException(nameof(inlineConstraintResolver)); - } - - if (displayName == null) - { - throw new ArgumentNullException(nameof(displayName)); - } + ArgumentNullException.ThrowIfNull(inlineConstraintResolver); + ArgumentNullException.ThrowIfNull(displayName); _inlineConstraintResolver = inlineConstraintResolver; _displayName = displayName; @@ -93,15 +86,8 @@ public IDictionary Build() /// public void AddConstraint(string key, object value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); var constraint = value as IRouteConstraint; if (constraint == null) @@ -136,15 +122,8 @@ public void AddConstraint(string key, object value) /// public void AddResolvedConstraint(string key, string constraintText) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (constraintText == null) - { - throw new ArgumentNullException(nameof(constraintText)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(constraintText); var constraint = _inlineConstraintResolver.ResolveConstraint(constraintText); if (constraint == null) @@ -171,10 +150,7 @@ public void AddResolvedConstraint(string key, string constraintText) /// The key. public void SetOptional(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); _optionalParameters.Add(key); } diff --git a/src/Http/Routing/src/RouteConstraintMatcher.cs b/src/Http/Routing/src/RouteConstraintMatcher.cs index 43022936ce9c..55f124ef44cc 100644 --- a/src/Http/Routing/src/RouteConstraintMatcher.cs +++ b/src/Http/Routing/src/RouteConstraintMatcher.cs @@ -32,25 +32,10 @@ public static bool Match( RouteDirection routeDirection, ILogger logger) { - if (routeValues == null) - { - throw new ArgumentNullException(nameof(routeValues)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (route == null) - { - throw new ArgumentNullException(nameof(route)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(routeValues); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(route); + ArgumentNullException.ThrowIfNull(logger); if (constraints == null || constraints.Count == 0) { diff --git a/src/Http/Routing/src/RouteEndpoint.cs b/src/Http/Routing/src/RouteEndpoint.cs index f84eb1e1fd64..a60d6b11995c 100644 --- a/src/Http/Routing/src/RouteEndpoint.cs +++ b/src/Http/Routing/src/RouteEndpoint.cs @@ -29,15 +29,8 @@ public RouteEndpoint( string? displayName) : base(requestDelegate, metadata, displayName) { - if (requestDelegate == null) - { - throw new ArgumentNullException(nameof(requestDelegate)); - } - - if (routePattern == null) - { - throw new ArgumentNullException(nameof(routePattern)); - } + ArgumentNullException.ThrowIfNull(requestDelegate); + ArgumentNullException.ThrowIfNull(routePattern); RoutePattern = routePattern; Order = order; diff --git a/src/Http/Routing/src/RouteOptions.cs b/src/Http/Routing/src/RouteOptions.cs index a1ef1ac8d158..4ae9a9688bf8 100644 --- a/src/Http/Routing/src/RouteOptions.cs +++ b/src/Http/Routing/src/RouteOptions.cs @@ -77,10 +77,7 @@ public IDictionary ConstraintMap } set { - if (value == null) - { - throw new ArgumentNullException(nameof(ConstraintMap)); - } + ArgumentNullException.ThrowIfNull(value); _constraintTypeMap = value; } diff --git a/src/Http/Routing/src/RouteValuesAddressScheme.cs b/src/Http/Routing/src/RouteValuesAddressScheme.cs index 95901f5153ca..2a2020a9ed53 100644 --- a/src/Http/Routing/src/RouteValuesAddressScheme.cs +++ b/src/Http/Routing/src/RouteValuesAddressScheme.cs @@ -21,10 +21,7 @@ public RouteValuesAddressScheme(EndpointDataSource dataSource) public IEnumerable FindEndpoints(RouteValuesAddress address) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); var state = State; diff --git a/src/Http/Routing/src/Template/DefaultTemplateBinderFactory.cs b/src/Http/Routing/src/Template/DefaultTemplateBinderFactory.cs index 8486970d8306..24a3567bcd96 100644 --- a/src/Http/Routing/src/Template/DefaultTemplateBinderFactory.cs +++ b/src/Http/Routing/src/Template/DefaultTemplateBinderFactory.cs @@ -16,15 +16,8 @@ public DefaultTemplateBinderFactory( ParameterPolicyFactory policyFactory, ObjectPool pool) { - if (policyFactory == null) - { - throw new ArgumentNullException(nameof(policyFactory)); - } - - if (pool == null) - { - throw new ArgumentNullException(nameof(pool)); - } + ArgumentNullException.ThrowIfNull(policyFactory); + ArgumentNullException.ThrowIfNull(pool); _policyFactory = policyFactory; _pool = pool; @@ -32,25 +25,15 @@ public DefaultTemplateBinderFactory( public override TemplateBinder Create(RouteTemplate template, RouteValueDictionary defaults) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } - - if (defaults == null) - { - throw new ArgumentNullException(nameof(defaults)); - } + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(defaults); return new TemplateBinder(UrlEncoder.Default, _pool, template, defaults); } public override TemplateBinder Create(RoutePattern pattern) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(pattern); // Now create the constraints and parameter transformers from the pattern var policies = new List<(string parameterName, IParameterPolicy policy)>(); diff --git a/src/Http/Routing/src/Template/InlineConstraint.cs b/src/Http/Routing/src/Template/InlineConstraint.cs index 3eec08ff1a60..3047465c8ba1 100644 --- a/src/Http/Routing/src/Template/InlineConstraint.cs +++ b/src/Http/Routing/src/Template/InlineConstraint.cs @@ -16,10 +16,7 @@ public class InlineConstraint /// The constraint text. public InlineConstraint(string constraint) { - if (constraint == null) - { - throw new ArgumentNullException(nameof(constraint)); - } + ArgumentNullException.ThrowIfNull(constraint); Constraint = constraint; } @@ -30,10 +27,7 @@ public InlineConstraint(string constraint) /// A instance. public InlineConstraint(RoutePatternParameterPolicyReference other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Constraint = other.Content!; } diff --git a/src/Http/Routing/src/Template/RouteTemplate.cs b/src/Http/Routing/src/Template/RouteTemplate.cs index 0b01658dd1ab..b8b29dac3032 100644 --- a/src/Http/Routing/src/Template/RouteTemplate.cs +++ b/src/Http/Routing/src/Template/RouteTemplate.cs @@ -23,10 +23,7 @@ public class RouteTemplate /// A instance. public RouteTemplate(RoutePattern other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); // RequiredValues will be ignored. RouteTemplate doesn't support them. @@ -55,10 +52,7 @@ public RouteTemplate(RoutePattern other) /// A list of . public RouteTemplate(string template, List segments) { - if (segments == null) - { - throw new ArgumentNullException(nameof(segments)); - } + ArgumentNullException.ThrowIfNull(segments); TemplateText = template; diff --git a/src/Http/Routing/src/Template/TemplateBinder.cs b/src/Http/Routing/src/Template/TemplateBinder.cs index 574e6f0edca1..4cbffa822430 100644 --- a/src/Http/Routing/src/Template/TemplateBinder.cs +++ b/src/Http/Routing/src/Template/TemplateBinder.cs @@ -68,20 +68,9 @@ internal TemplateBinder( IEnumerable? requiredKeys, IEnumerable<(string parameterName, IParameterPolicy policy)>? parameterPolicies) { - if (urlEncoder == null) - { - throw new ArgumentNullException(nameof(urlEncoder)); - } - - if (pool == null) - { - throw new ArgumentNullException(nameof(pool)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(urlEncoder); + ArgumentNullException.ThrowIfNull(pool); + ArgumentNullException.ThrowIfNull(pattern); _urlEncoder = urlEncoder; _pool = pool; @@ -116,20 +105,9 @@ internal TemplateBinder( RoutePattern pattern, IEnumerable<(string parameterName, IParameterPolicy policy)> parameterPolicies) { - if (urlEncoder == null) - { - throw new ArgumentNullException(nameof(urlEncoder)); - } - - if (pool == null) - { - throw new ArgumentNullException(nameof(pool)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(urlEncoder); + ArgumentNullException.ThrowIfNull(pool); + ArgumentNullException.ThrowIfNull(pattern); // Parameter policies can be null. diff --git a/src/Http/Routing/src/Template/TemplateMatcher.cs b/src/Http/Routing/src/Template/TemplateMatcher.cs index 4cb2a2a088a6..b94afa1c0522 100644 --- a/src/Http/Routing/src/Template/TemplateMatcher.cs +++ b/src/Http/Routing/src/Template/TemplateMatcher.cs @@ -27,10 +27,7 @@ public TemplateMatcher( RouteTemplate template, RouteValueDictionary defaults) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); Template = template; Defaults = defaults ?? new RouteValueDictionary(); @@ -83,10 +80,7 @@ public TemplateMatcher( /// if matches . public bool TryMatch(PathString path, RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); return _routePatternMatcher.TryMatch(path, values); } diff --git a/src/Http/Routing/src/Template/TemplateParser.cs b/src/Http/Routing/src/Template/TemplateParser.cs index 4bfe68a5c97f..2fafb2f96660 100644 --- a/src/Http/Routing/src/Template/TemplateParser.cs +++ b/src/Http/Routing/src/Template/TemplateParser.cs @@ -17,10 +17,7 @@ public static class TemplateParser /// A instance. public static RouteTemplate Parse(string routeTemplate) { - if (routeTemplate == null) - { - throw new ArgumentNullException(nameof(routeTemplate)); - } + ArgumentNullException.ThrowIfNull(routeTemplate); try { diff --git a/src/Http/Routing/src/Template/TemplatePart.cs b/src/Http/Routing/src/Template/TemplatePart.cs index 0f2c904089ac..b0f1ef02b1ab 100644 --- a/src/Http/Routing/src/Template/TemplatePart.cs +++ b/src/Http/Routing/src/Template/TemplatePart.cs @@ -84,10 +84,7 @@ public static TemplatePart CreateParameter( object? defaultValue, IEnumerable? inlineConstraints) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return new TemplatePart() { diff --git a/src/Http/Routing/src/Template/TemplateSegment.cs b/src/Http/Routing/src/Template/TemplateSegment.cs index b6c8825f2f6f..1b21f0fd067a 100644 --- a/src/Http/Routing/src/Template/TemplateSegment.cs +++ b/src/Http/Routing/src/Template/TemplateSegment.cs @@ -27,10 +27,7 @@ public TemplateSegment() /// A instance. public TemplateSegment(RoutePatternPathSegment other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); var partCount = other.Parts.Count; Parts = new List(partCount); diff --git a/src/Http/Routing/src/Tree/TreeRouteBuilder.cs b/src/Http/Routing/src/Tree/TreeRouteBuilder.cs index 9aed832cbba8..5f7d2f80a303 100644 --- a/src/Http/Routing/src/Tree/TreeRouteBuilder.cs +++ b/src/Http/Routing/src/Tree/TreeRouteBuilder.cs @@ -33,20 +33,9 @@ internal TreeRouteBuilder( ObjectPool objectPool, IInlineConstraintResolver constraintResolver) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (objectPool == null) - { - throw new ArgumentNullException(nameof(objectPool)); - } - - if (constraintResolver == null) - { - throw new ArgumentNullException(nameof(constraintResolver)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(objectPool); + ArgumentNullException.ThrowIfNull(constraintResolver); _urlEncoder = UrlEncoder.Default; _objectPool = objectPool; @@ -70,15 +59,8 @@ public InboundRouteEntry MapInbound( string routeName, int order) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - - if (routeTemplate == null) - { - throw new ArgumentNullException(nameof(routeTemplate)); - } + ArgumentNullException.ThrowIfNull(handler); + ArgumentNullException.ThrowIfNull(routeTemplate); var entry = new InboundRouteEntry() { @@ -137,20 +119,9 @@ public OutboundRouteEntry MapOutbound( string routeName, int order) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - - if (routeTemplate == null) - { - throw new ArgumentNullException(nameof(routeTemplate)); - } - - if (requiredLinkValues == null) - { - throw new ArgumentNullException(nameof(requiredLinkValues)); - } + ArgumentNullException.ThrowIfNull(handler); + ArgumentNullException.ThrowIfNull(routeTemplate); + ArgumentNullException.ThrowIfNull(requiredLinkValues); var entry = new OutboundRouteEntry() { diff --git a/src/Http/Routing/src/Tree/TreeRouter.cs b/src/Http/Routing/src/Tree/TreeRouter.cs index 66e9c76669c2..dc1b3967e740 100644 --- a/src/Http/Routing/src/Tree/TreeRouter.cs +++ b/src/Http/Routing/src/Tree/TreeRouter.cs @@ -48,35 +48,12 @@ internal TreeRouter( ILogger constraintLogger, int version) { - if (trees == null) - { - throw new ArgumentNullException(nameof(trees)); - } - - if (linkGenerationEntries == null) - { - throw new ArgumentNullException(nameof(linkGenerationEntries)); - } - - if (urlEncoder == null) - { - throw new ArgumentNullException(nameof(urlEncoder)); - } - - if (objectPool == null) - { - throw new ArgumentNullException(nameof(objectPool)); - } - - if (routeLogger == null) - { - throw new ArgumentNullException(nameof(routeLogger)); - } - - if (constraintLogger == null) - { - throw new ArgumentNullException(nameof(constraintLogger)); - } + ArgumentNullException.ThrowIfNull(trees); + ArgumentNullException.ThrowIfNull(linkGenerationEntries); + ArgumentNullException.ThrowIfNull(urlEncoder); + ArgumentNullException.ThrowIfNull(objectPool); + ArgumentNullException.ThrowIfNull(routeLogger); + ArgumentNullException.ThrowIfNull(constraintLogger); _trees = trees; _logger = routeLogger; @@ -133,10 +110,7 @@ internal TreeRouter( /// public VirtualPathData GetVirtualPath(VirtualPathContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // If it's a named route we will try to generate a link directly and // if we can't, we will not try to generate it using an unnamed route. diff --git a/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs index 0b496b396c30..dfcd66ea30dd 100644 --- a/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs +++ b/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs @@ -1103,10 +1103,7 @@ class TestConsumesAttribute : Attribute, IAcceptsMetadata { public TestConsumesAttribute(Type requestType, string contentType, params string[] otherContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); var contentTypes = new List() { diff --git a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcher.cs index dfb1f5215383..8fbdd672d5f7 100644 --- a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcher.cs +++ b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcher.cs @@ -19,10 +19,7 @@ public BarebonesMatcher(InnerMatcher[] matchers) public override Task MatchAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var path = httpContext.Request.Path.Value; for (var i = 0; i < Matchers.Length; i++) diff --git a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs index 6dab14656e84..312cf0ed8ca9 100644 --- a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs +++ b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs @@ -17,10 +17,7 @@ internal RouteMatcher(RouteCollection inner) public override async Task MatchAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var routeContext = new RouteContext(httpContext); await _inner.RouteAsync(routeContext); diff --git a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs index ce25b5a3f583..39f47668743d 100644 --- a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs +++ b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs @@ -18,10 +18,7 @@ internal TreeRouterMatcher(TreeRouter inner) public override async Task MatchAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var routeContext = new RouteContext(httpContext); await _inner.RouteAsync(routeContext); diff --git a/src/Http/Routing/test/testassets/RoutingSandbox/Framework/FrameworkEndpointRouteBuilderExtensions.cs b/src/Http/Routing/test/testassets/RoutingSandbox/Framework/FrameworkEndpointRouteBuilderExtensions.cs index dc5659de8c0c..af0222e3926e 100644 --- a/src/Http/Routing/test/testassets/RoutingSandbox/Framework/FrameworkEndpointRouteBuilderExtensions.cs +++ b/src/Http/Routing/test/testassets/RoutingSandbox/Framework/FrameworkEndpointRouteBuilderExtensions.cs @@ -7,14 +7,8 @@ public static class FrameworkEndpointRouteBuilderExtensions { public static IEndpointConventionBuilder MapFramework(this IEndpointRouteBuilder endpoints, Action configure) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(configure); var dataSource = endpoints.ServiceProvider.GetRequiredService(); diff --git a/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/EndpointRouteBuilderExtensions.cs b/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/EndpointRouteBuilderExtensions.cs index 634105d2f237..25c262fec5ff 100644 --- a/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/EndpointRouteBuilderExtensions.cs +++ b/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/EndpointRouteBuilderExtensions.cs @@ -7,10 +7,7 @@ public static class EndpointRouteBuilderExtensions { public static IEndpointConventionBuilder MapHello(this IEndpointRouteBuilder endpoints, string pattern, string greeter) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); var pipeline = endpoints.CreateApplicationBuilder() .UseHello(greeter) diff --git a/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/HelloAppBuilderExtensions.cs b/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/HelloAppBuilderExtensions.cs index a727aaf29597..a26cc92f0349 100644 --- a/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/HelloAppBuilderExtensions.cs +++ b/src/Http/Routing/test/testassets/RoutingSandbox/HelloExtension/HelloAppBuilderExtensions.cs @@ -10,10 +10,7 @@ public static class HelloAppBuilderExtensions { public static IApplicationBuilder UseHello(this IApplicationBuilder app, string greeter) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(Options.Create(new HelloOptions { diff --git a/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/EndpointRouteBuilderExtensions.cs b/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/EndpointRouteBuilderExtensions.cs index a379e24c5d11..41f0e3ac892e 100644 --- a/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/EndpointRouteBuilderExtensions.cs +++ b/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/EndpointRouteBuilderExtensions.cs @@ -7,10 +7,7 @@ public static class EndpointRouteBuilderExtensions { public static IEndpointConventionBuilder MapHello(this IEndpointRouteBuilder endpoints, string template, string greeter) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); var pipeline = endpoints.CreateApplicationBuilder() .UseHello(greeter) diff --git a/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/HelloAppBuilderExtensions.cs b/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/HelloAppBuilderExtensions.cs index d261206dff71..7c63e0341ea0 100644 --- a/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/HelloAppBuilderExtensions.cs +++ b/src/Http/Routing/test/testassets/RoutingWebSite/HelloExtension/HelloAppBuilderExtensions.cs @@ -10,10 +10,7 @@ public static class HelloAppBuilderExtensions { public static IApplicationBuilder UseHello(this IApplicationBuilder app, string greeter) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(Options.Create(new HelloOptions { diff --git a/src/Http/WebUtilities/src/BufferedReadStream.cs b/src/Http/WebUtilities/src/BufferedReadStream.cs index ef6562dc2f95..46bba74a4f97 100644 --- a/src/Http/WebUtilities/src/BufferedReadStream.cs +++ b/src/Http/WebUtilities/src/BufferedReadStream.cs @@ -40,10 +40,7 @@ public BufferedReadStream(Stream inner, int bufferSize) /// ArrayPool for the buffer. public BufferedReadStream(Stream inner, int bufferSize, ArrayPool bytePool) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullException.ThrowIfNull(inner); _inner = inner; _bytePool = bytePool; diff --git a/src/Http/WebUtilities/src/FileBufferingReadStream.cs b/src/Http/WebUtilities/src/FileBufferingReadStream.cs index 898b6299a754..4326991ed4c2 100644 --- a/src/Http/WebUtilities/src/FileBufferingReadStream.cs +++ b/src/Http/WebUtilities/src/FileBufferingReadStream.cs @@ -73,15 +73,8 @@ public FileBufferingReadStream( Func tempFileDirectoryAccessor, ArrayPool bytePool) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } - - if (tempFileDirectoryAccessor == null) - { - throw new ArgumentNullException(nameof(tempFileDirectoryAccessor)); - } + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(tempFileDirectoryAccessor); _bytePool = bytePool; if (memoryThreshold <= _maxRentedBufferSize) @@ -132,15 +125,8 @@ public FileBufferingReadStream( string tempFileDirectory, ArrayPool bytePool) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } - - if (tempFileDirectory == null) - { - throw new ArgumentNullException(nameof(tempFileDirectory)); - } + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(tempFileDirectory); _bytePool = bytePool; if (memoryThreshold <= _maxRentedBufferSize) diff --git a/src/Http/WebUtilities/src/FileBufferingWriteStream.cs b/src/Http/WebUtilities/src/FileBufferingWriteStream.cs index 1df345686dc2..edf490d54316 100644 --- a/src/Http/WebUtilities/src/FileBufferingWriteStream.cs +++ b/src/Http/WebUtilities/src/FileBufferingWriteStream.cs @@ -41,10 +41,7 @@ public FileBufferingWriteStream( long? bufferLimit = null, Func? tempFileDirectoryAccessor = null) { - if (memoryThreshold < 0) - { - throw new ArgumentOutOfRangeException(nameof(memoryThreshold)); - } + ArgumentOutOfRangeException.ThrowIfNegative(memoryThreshold); if (bufferLimit != null && bufferLimit < memoryThreshold) { diff --git a/src/Http/WebUtilities/src/FormReader.cs b/src/Http/WebUtilities/src/FormReader.cs index e0875c97da3b..2daa9920d126 100644 --- a/src/Http/WebUtilities/src/FormReader.cs +++ b/src/Http/WebUtilities/src/FormReader.cs @@ -59,10 +59,7 @@ public FormReader(string data) /// The to use. public FormReader(string data, ArrayPool charPool) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); _buffer = charPool.Rent(_rentedCharPoolLength); _charPool = charPool; @@ -96,15 +93,8 @@ public FormReader(Stream stream, Encoding encoding) /// The to use. public FormReader(Stream stream, Encoding encoding, ArrayPool charPool) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(encoding); _buffer = charPool.Rent(_rentedCharPoolLength); _charPool = charPool; diff --git a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs index edb97c846513..82c54c68e047 100644 --- a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs +++ b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs @@ -74,10 +74,7 @@ public HttpRequestStreamReader( _bytePool = bytePool ?? throw new ArgumentNullException(nameof(bytePool)); _charPool = charPool ?? throw new ArgumentNullException(nameof(charPool)); - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); if (!stream.CanRead) { throw new ArgumentException(Resources.HttpRequestStreamReader_StreamNotReadable, nameof(stream)); @@ -155,15 +152,8 @@ public override int Read() /// public override int Read(char[] buffer, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (count < 0 || index + count > buffer.Length) { @@ -228,15 +218,8 @@ public override int Read(Span buffer) /// public override Task ReadAsync(char[] buffer, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (count < 0 || index + count > buffer.Length) { diff --git a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs index 93207cd90452..a75c6826f54c 100644 --- a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs +++ b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs @@ -70,10 +70,7 @@ public HttpResponseStreamWriter( _bytePool = bytePool ?? throw new ArgumentNullException(nameof(bytePool)); _charPool = charPool ?? throw new ArgumentNullException(nameof(charPool)); - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); if (!_stream.CanWrite) { throw new ArgumentException(Resources.HttpResponseStreamWriter_StreamNotWritable, nameof(stream)); diff --git a/src/Http/WebUtilities/src/Microsoft.AspNetCore.WebUtilities.csproj b/src/Http/WebUtilities/src/Microsoft.AspNetCore.WebUtilities.csproj index 3958d23f0148..7daec005cf6d 100644 --- a/src/Http/WebUtilities/src/Microsoft.AspNetCore.WebUtilities.csproj +++ b/src/Http/WebUtilities/src/Microsoft.AspNetCore.WebUtilities.csproj @@ -16,6 +16,9 @@ + + + diff --git a/src/Http/WebUtilities/src/MultipartBoundary.cs b/src/Http/WebUtilities/src/MultipartBoundary.cs index efdc5eaf23dc..a5d592902e46 100644 --- a/src/Http/WebUtilities/src/MultipartBoundary.cs +++ b/src/Http/WebUtilities/src/MultipartBoundary.cs @@ -13,10 +13,7 @@ internal sealed class MultipartBoundary public MultipartBoundary(string boundary, bool expectLeadingCrlf = true) { - if (boundary == null) - { - throw new ArgumentNullException(nameof(boundary)); - } + ArgumentNullException.ThrowIfNull(boundary); _boundary = boundary; _expectLeadingCrlf = expectLeadingCrlf; diff --git a/src/Http/WebUtilities/src/MultipartReader.cs b/src/Http/WebUtilities/src/MultipartReader.cs index e8be2fe032c4..112950bbf170 100644 --- a/src/Http/WebUtilities/src/MultipartReader.cs +++ b/src/Http/WebUtilities/src/MultipartReader.cs @@ -47,15 +47,8 @@ public MultipartReader(string boundary, Stream stream) /// The minimum buffer size to use. public MultipartReader(string boundary, Stream stream, int bufferSize) { - if (boundary == null) - { - throw new ArgumentNullException(nameof(boundary)); - } - - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(boundary); + ArgumentNullException.ThrowIfNull(stream); if (bufferSize < boundary.Length + 8) // Size of the boundary + leading and trailing CRLF + leading and trailing '--' markers. { diff --git a/src/Http/WebUtilities/src/MultipartReaderStream.cs b/src/Http/WebUtilities/src/MultipartReaderStream.cs index 3423b1bce453..5bffde8e2d31 100644 --- a/src/Http/WebUtilities/src/MultipartReaderStream.cs +++ b/src/Http/WebUtilities/src/MultipartReaderStream.cs @@ -35,15 +35,8 @@ public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary bounda /// The ArrayPool pool to use for temporary byte arrays. public MultipartReaderStream(BufferedReadStream stream, MultipartBoundary boundary, ArrayPool bytePool) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (boundary == null) - { - throw new ArgumentNullException(nameof(boundary)); - } + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(boundary); _bytePool = bytePool; _innerStream = stream; diff --git a/src/Http/WebUtilities/src/MultipartSectionConverterExtensions.cs b/src/Http/WebUtilities/src/MultipartSectionConverterExtensions.cs index b19800f8123d..28ad9c6692fb 100644 --- a/src/Http/WebUtilities/src/MultipartSectionConverterExtensions.cs +++ b/src/Http/WebUtilities/src/MultipartSectionConverterExtensions.cs @@ -17,10 +17,7 @@ public static class MultipartSectionConverterExtensions /// A file section public static FileMultipartSection? AsFileSection(this MultipartSection section) { - if (section == null) - { - throw new ArgumentNullException(nameof(section)); - } + ArgumentNullException.ThrowIfNull(section); try { @@ -39,10 +36,7 @@ public static class MultipartSectionConverterExtensions /// A form section public static FormMultipartSection? AsFormDataSection(this MultipartSection section) { - if (section == null) - { - throw new ArgumentNullException(nameof(section)); - } + ArgumentNullException.ThrowIfNull(section); try { diff --git a/src/Http/WebUtilities/src/QueryHelpers.cs b/src/Http/WebUtilities/src/QueryHelpers.cs index f3eeb344f737..0441447fb4ee 100644 --- a/src/Http/WebUtilities/src/QueryHelpers.cs +++ b/src/Http/WebUtilities/src/QueryHelpers.cs @@ -25,20 +25,9 @@ public static class QueryHelpers /// is null. public static string AddQueryString(string uri, string name, string value) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); return AddQueryString( uri, new[] { new KeyValuePair(name, value) }); @@ -54,15 +43,8 @@ public static string AddQueryString(string uri, string name, string value) /// is null. public static string AddQueryString(string uri, IDictionary queryString) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - - if (queryString == null) - { - throw new ArgumentNullException(nameof(queryString)); - } + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(queryString); return AddQueryString(uri, (IEnumerable>)queryString); } @@ -77,15 +59,8 @@ public static string AddQueryString(string uri, IDictionary que /// is null. public static string AddQueryString(string uri, IEnumerable> queryString) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - - if (queryString == null) - { - throw new ArgumentNullException(nameof(queryString)); - } + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(queryString); return AddQueryString(uri, queryString.SelectMany(kvp => kvp.Value, (kvp, v) => KeyValuePair.Create(kvp.Key, v))); } @@ -102,15 +77,8 @@ public static string AddQueryString( string uri, IEnumerable> queryString) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - - if (queryString == null) - { - throw new ArgumentNullException(nameof(queryString)); - } + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(queryString); var anchorIndex = uri.IndexOf('#'); var uriToBeAppended = uri.AsSpan(); diff --git a/src/Identity/ApiAuthorization.IdentityServer/samples/ApiAuthSample/Program.cs b/src/Identity/ApiAuthorization.IdentityServer/samples/ApiAuthSample/Program.cs index b3d78137f2b0..ac39c557d502 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/samples/ApiAuthSample/Program.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/samples/ApiAuthSample/Program.cs @@ -9,10 +9,7 @@ public class Program { public static void Main(string[] args) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); CreateWebHostBuilder(args).Build().Run(); } diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Extensions/RelativeRedirectUriValidator.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Extensions/RelativeRedirectUriValidator.cs index d6ba94860e2f..f13a809f2462 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/src/Extensions/RelativeRedirectUriValidator.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/src/Extensions/RelativeRedirectUriValidator.cs @@ -10,10 +10,7 @@ internal sealed class RelativeRedirectUriValidator : StrictRedirectUriValidator { public RelativeRedirectUriValidator(IAbsoluteUrlFactory absoluteUrlFactory) { - if (absoluteUrlFactory == null) - { - throw new ArgumentNullException(nameof(absoluteUrlFactory)); - } + ArgumentNullException.ThrowIfNull(absoluteUrlFactory); AbsoluteUrlFactory = absoluteUrlFactory; } diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/IdentityServerBuilderConfigurationExtensions.cs b/src/Identity/ApiAuthorization.IdentityServer/src/IdentityServerBuilderConfigurationExtensions.cs index 3f37b4adb24e..9fbf73bbdc90 100644 --- a/src/Identity/ApiAuthorization.IdentityServer/src/IdentityServerBuilderConfigurationExtensions.cs +++ b/src/Identity/ApiAuthorization.IdentityServer/src/IdentityServerBuilderConfigurationExtensions.cs @@ -53,10 +53,7 @@ public static IIdentityServerBuilder AddApiAuthorization( where TUser : class where TContext : DbContext, IPersistedGrantDbContext { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); builder.AddAspNetIdentity() .AddOperationalStore() diff --git a/src/Identity/Core/src/DataProtectorTokenProvider.cs b/src/Identity/Core/src/DataProtectorTokenProvider.cs index 603bee536e4b..df4a878f9fa3 100644 --- a/src/Identity/Core/src/DataProtectorTokenProvider.cs +++ b/src/Identity/Core/src/DataProtectorTokenProvider.cs @@ -25,10 +25,7 @@ public DataProtectorTokenProvider(IDataProtectionProvider dataProtectionProvider IOptions options, ILogger> logger) { - if (dataProtectionProvider == null) - { - throw new ArgumentNullException(nameof(dataProtectionProvider)); - } + ArgumentNullException.ThrowIfNull(dataProtectionProvider); Options = options?.Value ?? new DataProtectionTokenProviderOptions(); @@ -78,10 +75,7 @@ public DataProtectorTokenProvider(IDataProtectionProvider dataProtectionProvider /// A representing the generated token. public virtual async Task GenerateAsync(string purpose, UserManager manager, TUser user) { - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var ms = new MemoryStream(); var userId = await manager.GetUserIdAsync(user); using (var writer = ms.CreateWriter()) diff --git a/src/Identity/Core/src/SecurityStampValidator.cs b/src/Identity/Core/src/SecurityStampValidator.cs index a65f24430456..f07d1f00f248 100644 --- a/src/Identity/Core/src/SecurityStampValidator.cs +++ b/src/Identity/Core/src/SecurityStampValidator.cs @@ -25,14 +25,8 @@ public class SecurityStampValidator : ISecurityStampValidator where TUser /// The logger. public SecurityStampValidator(IOptions options, SignInManager signInManager, ISystemClock clock, ILoggerFactory logger) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (signInManager == null) - { - throw new ArgumentNullException(nameof(signInManager)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(signInManager); SignInManager = signInManager; Options = options.Value; Clock = clock; diff --git a/src/Identity/Core/src/SignInManager.cs b/src/Identity/Core/src/SignInManager.cs index 3f90b4c241ad..450b241b84b5 100644 --- a/src/Identity/Core/src/SignInManager.cs +++ b/src/Identity/Core/src/SignInManager.cs @@ -38,18 +38,9 @@ public SignInManager(UserManager userManager, IAuthenticationSchemeProvider schemes, IUserConfirmation confirmation) { - if (userManager == null) - { - throw new ArgumentNullException(nameof(userManager)); - } - if (contextAccessor == null) - { - throw new ArgumentNullException(nameof(contextAccessor)); - } - if (claimsFactory == null) - { - throw new ArgumentNullException(nameof(claimsFactory)); - } + ArgumentNullException.ThrowIfNull(userManager); + ArgumentNullException.ThrowIfNull(contextAccessor); + ArgumentNullException.ThrowIfNull(claimsFactory); UserManager = userManager; _contextAccessor = contextAccessor; @@ -122,10 +113,7 @@ public HttpContext Context /// True if the user is logged in with identity. public virtual bool IsSignedIn(ClaimsPrincipal principal) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullException.ThrowIfNull(principal); return principal.Identities != null && principal.Identities.Any(i => i.AuthenticationType == IdentityConstants.ApplicationScheme); } @@ -327,10 +315,7 @@ public virtual async Task ValidateSecurityStampAsync(TUser? user, string? public virtual async Task PasswordSignInAsync(TUser user, string password, bool isPersistent, bool lockoutOnFailure) { - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var attempt = await CheckPasswordSignInAsync(user, password, lockoutOnFailure); return attempt.Succeeded @@ -371,10 +356,7 @@ public virtual async Task PasswordSignInAsync(string userName, str /// public virtual async Task CheckPasswordSignInAsync(TUser user, string password, bool lockoutOnFailure) { - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var error = await PreSignInCheck(user); if (error != null) @@ -688,10 +670,7 @@ public virtual async Task> GetExternalAuthenti /// The that represents the asynchronous operation, containing the of the operation. public virtual async Task UpdateExternalAuthenticationTokensAsync(ExternalLoginInfo externalLogin) { - if (externalLogin == null) - { - throw new ArgumentNullException(nameof(externalLogin)); - } + ArgumentNullException.ThrowIfNull(externalLogin); if (externalLogin.AuthenticationTokens != null && externalLogin.AuthenticationTokens.Any()) { diff --git a/src/Identity/EntityFrameworkCore/src/RoleStore.cs b/src/Identity/EntityFrameworkCore/src/RoleStore.cs index 19955565ea54..e77cc173dada 100644 --- a/src/Identity/EntityFrameworkCore/src/RoleStore.cs +++ b/src/Identity/EntityFrameworkCore/src/RoleStore.cs @@ -85,10 +85,7 @@ public class RoleStore : /// The . public RoleStore(TContext context, IdentityErrorDescriber? describer = null) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); Context = context; ErrorDescriber = describer ?? new IdentityErrorDescriber(); } @@ -134,10 +131,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); Context.Add(role); await SaveChanges(cancellationToken); return IdentityResult.Success; @@ -153,10 +147,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); Context.Attach(role); role.ConcurrencyStamp = Guid.NewGuid().ToString(); Context.Update(role); @@ -181,10 +172,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); Context.Remove(role); try { @@ -207,10 +195,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); return Task.FromResult(ConvertIdToString(role.Id)!); } @@ -224,10 +209,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); return Task.FromResult(role.Name); } @@ -242,10 +224,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); role.Name = roleName; return Task.CompletedTask; } @@ -315,10 +294,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); return Task.FromResult(role.NormalizedName); } @@ -333,10 +309,7 @@ protected virtual async Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); role.NormalizedName = normalizedName; return Task.CompletedTask; } @@ -363,10 +336,7 @@ protected void ThrowIfDisposed() public virtual async Task> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullException.ThrowIfNull(role); return await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id)).Select(c => new Claim(c.ClaimType!, c.ClaimValue!)).ToListAsync(cancellationToken); } @@ -381,14 +351,8 @@ protected void ThrowIfDisposed() public virtual Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(role); + ArgumentNullException.ThrowIfNull(claim); RoleClaims.Add(CreateRoleClaim(role, claim)); return Task.FromResult(false); @@ -404,14 +368,8 @@ protected void ThrowIfDisposed() public virtual async Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(role); + ArgumentNullException.ThrowIfNull(claim); var claims = await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id) && rc.ClaimValue == claim.Value && rc.ClaimType == claim.Type).ToListAsync(cancellationToken); foreach (var c in claims) { diff --git a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs index 6e85416a3205..a363eebd604c 100644 --- a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs +++ b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs @@ -95,10 +95,7 @@ public class UserOnlyStoreThe used to describe store errors. public UserOnlyStore(TContext context, IdentityErrorDescriber? describer = null) : base(describer ?? new IdentityErrorDescriber()) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); Context = context; } @@ -153,10 +150,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Add(user); await SaveChanges(cancellationToken); return IdentityResult.Success; @@ -172,10 +166,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Attach(user); user.ConcurrencyStamp = Guid.NewGuid().ToString(); @@ -201,10 +192,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Remove(user); try @@ -303,10 +291,7 @@ public override IQueryable Users public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); return await UserClaims.Where(uc => uc.UserId.Equals(user.Id)).Select(c => c.ToClaim()).ToListAsync(cancellationToken); } @@ -321,14 +306,8 @@ public override IQueryable Users public override Task AddClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claims); foreach (var claim in claims) { UserClaims.Add(CreateUserClaim(user, claim)); @@ -347,18 +326,9 @@ public override IQueryable Users public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (newClaim == null) - { - throw new ArgumentNullException(nameof(newClaim)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claim); + ArgumentNullException.ThrowIfNull(newClaim); var matchedClaims = await UserClaims.Where(uc => uc.UserId.Equals(user.Id) && uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToListAsync(cancellationToken); foreach (var matchedClaim in matchedClaims) @@ -378,14 +348,8 @@ public override IQueryable Users public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claims); foreach (var claim in claims) { var matchedClaims = await UserClaims.Where(uc => uc.UserId.Equals(user.Id) && uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToListAsync(cancellationToken); @@ -408,14 +372,8 @@ public override Task AddLoginAsync(TUser user, UserLoginInfo login, { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (login == null) - { - throw new ArgumentNullException(nameof(login)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(login); UserLogins.Add(CreateUserLogin(user, login)); return Task.FromResult(false); } @@ -433,10 +391,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var entry = await FindUserLoginAsync(user.Id, loginProvider, providerKey, cancellationToken); if (entry != null) { @@ -456,10 +411,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var userId = user.Id; return await UserLogins.Where(l => l.UserId.Equals(userId)) .Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.ProviderDisplayName)).ToListAsync(cancellationToken); @@ -515,10 +467,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(claim); var query = from userclaims in UserClaims join user in Users on userclaims.UserId equals user.Id diff --git a/src/Identity/EntityFrameworkCore/src/UserStore.cs b/src/Identity/EntityFrameworkCore/src/UserStore.cs index e13662f26fb3..7b0530af36fb 100644 --- a/src/Identity/EntityFrameworkCore/src/UserStore.cs +++ b/src/Identity/EntityFrameworkCore/src/UserStore.cs @@ -110,10 +110,7 @@ public class UserStoreThe used to describe store errors. public UserStore(TContext context, IdentityErrorDescriber? describer = null) : base(describer ?? new IdentityErrorDescriber()) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); Context = context; } @@ -155,10 +152,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Add(user); await SaveChanges(cancellationToken); return IdentityResult.Success; @@ -174,10 +168,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Attach(user); user.ConcurrencyStamp = Guid.NewGuid().ToString(); @@ -203,10 +194,7 @@ protected Task SaveChanges(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); Context.Remove(user); try @@ -330,10 +318,7 @@ public override IQueryable Users { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, nameof(normalizedRoleName)); @@ -357,10 +342,7 @@ public override IQueryable Users { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, nameof(normalizedRoleName)); @@ -386,10 +368,7 @@ public override IQueryable Users { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var userId = user.Id; var query = from userRole in UserRoles join role in Roles on userRole.RoleId equals role.Id @@ -410,10 +389,7 @@ where userRole.UserId.Equals(userId) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException(Resources.ValueCannotBeNullOrEmpty, nameof(normalizedRoleName)); @@ -436,10 +412,7 @@ where userRole.UserId.Equals(userId) public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); return await UserClaims.Where(uc => uc.UserId.Equals(user.Id)).Select(c => c.ToClaim()).ToListAsync(cancellationToken); } @@ -454,14 +427,8 @@ where userRole.UserId.Equals(userId) public override Task AddClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claims); foreach (var claim in claims) { UserClaims.Add(CreateUserClaim(user, claim)); @@ -480,18 +447,9 @@ where userRole.UserId.Equals(userId) public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (newClaim == null) - { - throw new ArgumentNullException(nameof(newClaim)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claim); + ArgumentNullException.ThrowIfNull(newClaim); var matchedClaims = await UserClaims.Where(uc => uc.UserId.Equals(user.Id) && uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToListAsync(cancellationToken); foreach (var matchedClaim in matchedClaims) @@ -511,14 +469,8 @@ where userRole.UserId.Equals(userId) public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(claims); foreach (var claim in claims) { var matchedClaims = await UserClaims.Where(uc => uc.UserId.Equals(user.Id) && uc.ClaimValue == claim.Value && uc.ClaimType == claim.Type).ToListAsync(cancellationToken); @@ -541,14 +493,8 @@ public override Task AddLoginAsync(TUser user, UserLoginInfo login, { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (login == null) - { - throw new ArgumentNullException(nameof(login)); - } + ArgumentNullException.ThrowIfNull(user); + ArgumentNullException.ThrowIfNull(login); UserLogins.Add(CreateUserLogin(user, login)); return Task.FromResult(false); } @@ -566,10 +512,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var entry = await FindUserLoginAsync(user.Id, loginProvider, providerKey, cancellationToken); if (entry != null) { @@ -589,10 +532,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); var userId = user.Id; return await UserLogins.Where(l => l.UserId.Equals(userId)) .Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey, l.ProviderDisplayName)).ToListAsync(cancellationToken); @@ -648,10 +588,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(claim); var query = from userclaims in UserClaims join user in Users on userclaims.UserId equals user.Id diff --git a/src/Identity/Extensions.Core/src/Base32.cs b/src/Identity/Extensions.Core/src/Base32.cs index 13effd61a075..a1397dcc6dec 100644 --- a/src/Identity/Extensions.Core/src/Base32.cs +++ b/src/Identity/Extensions.Core/src/Base32.cs @@ -4,6 +4,7 @@ using System; using System.Security.Cryptography; using System.Text; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -49,10 +50,7 @@ public static string GenerateBase32() public static string ToBase32(byte[] input) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); StringBuilder sb = new StringBuilder(); for (int offset = 0; offset < input.Length;) @@ -75,10 +73,7 @@ public static string ToBase32(byte[] input) public static byte[] FromBase32(string input) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); var trimmedInput = input.AsSpan().TrimEnd('='); if (trimmedInput.Length == 0) { diff --git a/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj b/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj index c32a5404cf79..87e7f976b40d 100644 --- a/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj +++ b/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj @@ -17,6 +17,8 @@ + + + + diff --git a/src/Identity/test/InMemory.Test/InMemoryUserStore.cs b/src/Identity/test/InMemory.Test/InMemoryUserStore.cs index 13b37530e8e6..807e82e3f993 100644 --- a/src/Identity/test/InMemory.Test/InMemoryUserStore.cs +++ b/src/Identity/test/InMemory.Test/InMemoryUserStore.cs @@ -333,10 +333,7 @@ public void Dispose() public Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(claim); var query = from user in Users where user.Claims.Where(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value).FirstOrDefault() != null diff --git a/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReference.cs b/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReference.cs index 56de56eedb2c..29e3e5827806 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReference.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/DotNetObjectReference.cs @@ -18,10 +18,7 @@ public static class DotNetObjectReference /// An instance of . public static DotNetObjectReference Create<[DynamicallyAccessedMembers(JSInvokable)] TValue>(TValue value) where TValue : class { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); return new DotNetObjectReference(value); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSInProcessObjectReferenceExtensions.cs b/src/JSInterop/Microsoft.JSInterop/src/JSInProcessObjectReferenceExtensions.cs index 233837c37963..f31f3aaed1f0 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSInProcessObjectReferenceExtensions.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSInProcessObjectReferenceExtensions.cs @@ -20,10 +20,7 @@ public static class JSInProcessObjectReferenceExtensions [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The method returns void, so nothing is deserialized.")] public static void InvokeVoid(this IJSInProcessObjectReference jsObjectReference, string identifier, params object?[]? args) { - if (jsObjectReference == null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); jsObjectReference.Invoke(identifier, args); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSInProcessRuntimeExtensions.cs b/src/JSInterop/Microsoft.JSInterop/src/JSInProcessRuntimeExtensions.cs index 231330763228..40bbbc8ba158 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSInProcessRuntimeExtensions.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSInProcessRuntimeExtensions.cs @@ -20,10 +20,7 @@ public static class JSInProcessRuntimeExtensions [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The method returns void, so nothing is deserialized.")] public static void InvokeVoid(this IJSInProcessRuntime jsRuntime, string identifier, params object?[]? args) { - if (jsRuntime == null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); jsRuntime.Invoke(identifier, args); } diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSObjectReferenceExtensions.cs b/src/JSInterop/Microsoft.JSInterop/src/JSObjectReferenceExtensions.cs index 69700fe6b9ed..01066efb3dc5 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSObjectReferenceExtensions.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSObjectReferenceExtensions.cs @@ -21,10 +21,7 @@ public static class JSObjectReferenceExtensions /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectReference, string identifier, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); await jsObjectReference.InvokeAsync(identifier, args); } @@ -43,10 +40,7 @@ public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectRe /// An instance of obtained by JSON-deserializing the return value. public static ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSObjectReference jsObjectReference, string identifier, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); return jsObjectReference.InvokeAsync(identifier, args); } @@ -65,10 +59,7 @@ public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectRe /// An instance of obtained by JSON-deserializing the return value. public static ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSObjectReference jsObjectReference, string identifier, CancellationToken cancellationToken, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); return jsObjectReference.InvokeAsync(identifier, cancellationToken, args); } @@ -86,10 +77,7 @@ public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectRe /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectReference, string identifier, CancellationToken cancellationToken, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); await jsObjectReference.InvokeAsync(identifier, cancellationToken, args); } @@ -104,10 +92,7 @@ public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectRe /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSObjectReference jsObjectReference, string identifier, TimeSpan timeout, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout); var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None; @@ -125,10 +110,7 @@ public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectRe /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSObjectReference jsObjectReference, string identifier, TimeSpan timeout, params object?[]? args) { - if (jsObjectReference is null) - { - throw new ArgumentNullException(nameof(jsObjectReference)); - } + ArgumentNullException.ThrowIfNull(jsObjectReference); using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout); var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None; diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs index d406ed1e6f15..3cbd024d2755 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSRuntime.cs @@ -294,10 +294,7 @@ internal long BeginTransmittingStream(DotNetStreamReference dotNetStreamReferenc internal long TrackObjectReference<[DynamicallyAccessedMembers(JSInvokable)] TValue>(DotNetObjectReference dotNetObjectReference) where TValue : class { - if (dotNetObjectReference == null) - { - throw new ArgumentNullException(nameof(dotNetObjectReference)); - } + ArgumentNullException.ThrowIfNull(dotNetObjectReference); dotNetObjectReference.ThrowIfDisposed(); diff --git a/src/JSInterop/Microsoft.JSInterop/src/JSRuntimeExtensions.cs b/src/JSInterop/Microsoft.JSInterop/src/JSRuntimeExtensions.cs index 4276990b9c51..5a4202ed15da 100644 --- a/src/JSInterop/Microsoft.JSInterop/src/JSRuntimeExtensions.cs +++ b/src/JSInterop/Microsoft.JSInterop/src/JSRuntimeExtensions.cs @@ -21,10 +21,7 @@ public static class JSRuntimeExtensions /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string identifier, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); await jsRuntime.InvokeAsync(identifier, args); } @@ -43,10 +40,7 @@ public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string /// An instance of obtained by JSON-deserializing the return value. public static ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSRuntime jsRuntime, string identifier, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); return jsRuntime.InvokeAsync(identifier, args); } @@ -65,10 +59,7 @@ public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string /// An instance of obtained by JSON-deserializing the return value. public static ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSRuntime jsRuntime, string identifier, CancellationToken cancellationToken, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); return jsRuntime.InvokeAsync(identifier, cancellationToken, args); } @@ -86,10 +77,7 @@ public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string identifier, CancellationToken cancellationToken, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); await jsRuntime.InvokeAsync(identifier, cancellationToken, args); } @@ -104,10 +92,7 @@ public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeAsync<[DynamicallyAccessedMembers(JsonSerialized)] TValue>(this IJSRuntime jsRuntime, string identifier, TimeSpan timeout, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout); var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None; @@ -125,10 +110,7 @@ public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string /// A that represents the asynchronous invocation operation. public static async ValueTask InvokeVoidAsync(this IJSRuntime jsRuntime, string identifier, TimeSpan timeout, params object?[]? args) { - if (jsRuntime is null) - { - throw new ArgumentNullException(nameof(jsRuntime)); - } + ArgumentNullException.ThrowIfNull(jsRuntime); using var cancellationTokenSource = timeout == Timeout.InfiniteTimeSpan ? null : new CancellationTokenSource(timeout); var cancellationToken = cancellationTokenSource?.Token ?? CancellationToken.None; diff --git a/src/Middleware/CORS/src/CorsServiceCollectionExtensions.cs b/src/Middleware/CORS/src/CorsServiceCollectionExtensions.cs index 29408d22c4c8..fc08d7bb9a69 100644 --- a/src/Middleware/CORS/src/CorsServiceCollectionExtensions.cs +++ b/src/Middleware/CORS/src/CorsServiceCollectionExtensions.cs @@ -18,10 +18,7 @@ public static class CorsServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddCors(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddOptions(); @@ -39,15 +36,8 @@ public static IServiceCollection AddCors(this IServiceCollection services) /// The so that additional calls can be chained. public static IServiceCollection AddCors(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); services.AddCors(); services.Configure(setupAction); diff --git a/src/Middleware/CORS/src/Infrastructure/CorsEndpointConventionBuilderExtensions.cs b/src/Middleware/CORS/src/Infrastructure/CorsEndpointConventionBuilderExtensions.cs index 70528eeabb98..a84f7a232f64 100644 --- a/src/Middleware/CORS/src/Infrastructure/CorsEndpointConventionBuilderExtensions.cs +++ b/src/Middleware/CORS/src/Infrastructure/CorsEndpointConventionBuilderExtensions.cs @@ -44,10 +44,7 @@ public static TBuilder RequireCors(this TBuilder builder, ActionThe original app parameter public static IApplicationBuilder UseCors(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -33,10 +30,7 @@ public static IApplicationBuilder UseCors(this IApplicationBuilder app) /// The original app parameter public static IApplicationBuilder UseCors(this IApplicationBuilder app, string policyName) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(policyName); } @@ -51,15 +45,8 @@ public static IApplicationBuilder UseCors( this IApplicationBuilder app, Action configurePolicy) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(configurePolicy); var policyBuilder = new CorsPolicyBuilder(); configurePolicy(policyBuilder); diff --git a/src/Middleware/CORS/src/Infrastructure/CorsOptions.cs b/src/Middleware/CORS/src/Infrastructure/CorsOptions.cs index a68c86dce791..fe3f825b062f 100644 --- a/src/Middleware/CORS/src/Infrastructure/CorsOptions.cs +++ b/src/Middleware/CORS/src/Infrastructure/CorsOptions.cs @@ -33,10 +33,7 @@ public string DefaultPolicyName /// The policy to be added. public void AddDefaultPolicy(CorsPolicy policy) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(policy); AddPolicy(DefaultPolicyName, policy); } @@ -47,10 +44,7 @@ public void AddDefaultPolicy(CorsPolicy policy) /// A delegate which can use a policy builder to build a policy. public void AddDefaultPolicy(Action configurePolicy) { - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullException.ThrowIfNull(configurePolicy); AddPolicy(DefaultPolicyName, configurePolicy); } @@ -62,15 +56,8 @@ public void AddDefaultPolicy(Action configurePolicy) /// The policy to be added. public void AddPolicy(string name, CorsPolicy policy) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(policy); PolicyMap[name] = (policy, Task.FromResult(policy)); } @@ -82,15 +69,8 @@ public void AddPolicy(string name, CorsPolicy policy) /// A delegate which can use a policy builder to build a policy. public void AddPolicy(string name, Action configurePolicy) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(configurePolicy); var policyBuilder = new CorsPolicyBuilder(); configurePolicy(policyBuilder); @@ -106,10 +86,7 @@ public void AddPolicy(string name, Action configurePolicy) /// The if the policy was added.null otherwise. public CorsPolicy? GetPolicy(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); if (PolicyMap.TryGetValue(name, out var result)) { diff --git a/src/Middleware/CORS/src/Infrastructure/CorsPolicyBuilder.cs b/src/Middleware/CORS/src/Infrastructure/CorsPolicyBuilder.cs index 68291bbfe115..878a36534d96 100644 --- a/src/Middleware/CORS/src/Infrastructure/CorsPolicyBuilder.cs +++ b/src/Middleware/CORS/src/Infrastructure/CorsPolicyBuilder.cs @@ -53,10 +53,7 @@ public CorsPolicyBuilder(CorsPolicy policy) /// public CorsPolicyBuilder WithOrigins(params string[] origins) { - if (origins is null) - { - throw new ArgumentNullException(nameof(origins)); - } + ArgumentNullException.ThrowIfNull(origins); foreach (var origin in origins) { @@ -69,10 +66,7 @@ public CorsPolicyBuilder WithOrigins(params string[] origins) internal static string GetNormalizedOrigin(string origin) { - if (origin is null) - { - throw new ArgumentNullException(nameof(origin)); - } + ArgumentNullException.ThrowIfNull(origin); if (Uri.TryCreate(origin, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && @@ -248,10 +242,7 @@ public CorsPolicy Build() /// The current policy builder. private CorsPolicyBuilder Combine(CorsPolicy policy) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(policy); WithOrigins(policy.Origins.ToArray()); WithHeaders(policy.Headers.ToArray()); diff --git a/src/Middleware/CORS/src/Infrastructure/CorsService.cs b/src/Middleware/CORS/src/Infrastructure/CorsService.cs index 445c1d16823a..aa46e4806a37 100644 --- a/src/Middleware/CORS/src/Infrastructure/CorsService.cs +++ b/src/Middleware/CORS/src/Infrastructure/CorsService.cs @@ -26,15 +26,8 @@ public class CorsService : ICorsService /// The . public CorsService(IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _options = options.Value; _logger = loggerFactory.CreateLogger(); @@ -50,10 +43,7 @@ public CorsService(IOptions options, ILoggerFactory loggerFactory) /// used by the caller to set appropriate response headers. public CorsResult EvaluatePolicy(HttpContext context, string policyName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var policy = _options.GetPolicy(policyName); if (policy is null) @@ -67,15 +57,8 @@ public CorsResult EvaluatePolicy(HttpContext context, string policyName) /// public CorsResult EvaluatePolicy(HttpContext context, CorsPolicy policy) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(policy); if (policy.AllowAnyOrigin && policy.SupportsCredentials) { @@ -168,15 +151,8 @@ public virtual void EvaluatePreflightRequest(HttpContext context, CorsPolicy pol /// public virtual void ApplyResult(CorsResult result, HttpResponse response) { - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } - - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } + ArgumentNullException.ThrowIfNull(result); + ArgumentNullException.ThrowIfNull(response); if (!result.IsOriginAllowed) { diff --git a/src/Middleware/CORS/src/Infrastructure/DefaultCorsPolicyProvider.cs b/src/Middleware/CORS/src/Infrastructure/DefaultCorsPolicyProvider.cs index a1c6f246d09f..6c68cf7ac047 100644 --- a/src/Middleware/CORS/src/Infrastructure/DefaultCorsPolicyProvider.cs +++ b/src/Middleware/CORS/src/Infrastructure/DefaultCorsPolicyProvider.cs @@ -24,10 +24,7 @@ public DefaultCorsPolicyProvider(IOptions options) /// public Task GetPolicyAsync(HttpContext context, string? policyName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); policyName ??= _options.DefaultPolicyName; if (_options.PolicyMap.TryGetValue(policyName, out var result)) diff --git a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/EchoMiddleware.cs b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/EchoMiddleware.cs index 66e1c28be69a..242f800ee988 100644 --- a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/EchoMiddleware.cs +++ b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/EchoMiddleware.cs @@ -22,10 +22,7 @@ public EchoMiddleware(RequestDelegate next) /// A that completes when writing to the response is done. public Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); context.Response.ContentType = "text/plain; charset=utf-8"; var path = context.Request.PathBase + context.Request.Path + context.Request.QueryString; diff --git a/src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterExtensions.cs b/src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterExtensions.cs index 7f26b58a9a55..d1efabe89711 100644 --- a/src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterExtensions.cs +++ b/src/Middleware/ConcurrencyLimiter/src/ConcurrencyLimiterExtensions.cs @@ -17,10 +17,7 @@ public static class ConcurrencyLimiterExtensions /// The . public static IApplicationBuilder UseConcurrencyLimiter(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseDeveloperPageExceptionFilterServiceExtensions.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseDeveloperPageExceptionFilterServiceExtensions.cs index 2aa2816abd34..9f1a08138bd4 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseDeveloperPageExceptionFilterServiceExtensions.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseDeveloperPageExceptionFilterServiceExtensions.cs @@ -23,10 +23,7 @@ public static class DatabaseDeveloperPageExceptionFilterServiceExtensions /// public static IServiceCollection AddDatabaseDeveloperPageExceptionFilter(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddEnumerable(new ServiceDescriptor(typeof(IDeveloperPageExceptionFilter), typeof(DatabaseDeveloperPageExceptionFilter), ServiceLifetime.Singleton)); diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageExtensions.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageExtensions.cs index 773792b2bca7..7525be3e5123 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageExtensions.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageExtensions.cs @@ -22,10 +22,7 @@ public static class DatabaseErrorPageExtensions [Obsolete("This is obsolete and will be removed in a future version. Use DatabaseDeveloperPageExceptionFilter instead, see documentation at https://aka.ms/DatabaseDeveloperPageExceptionFilter.")] public static IApplicationBuilder UseDatabaseErrorPage(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseDatabaseErrorPage(new DatabaseErrorPageOptions()); } @@ -41,15 +38,8 @@ public static IApplicationBuilder UseDatabaseErrorPage(this IApplicationBuilder public static IApplicationBuilder UseDatabaseErrorPage( this IApplicationBuilder app, DatabaseErrorPageOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); app = app.UseMiddleware(Options.Create(options)); diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageMiddleware.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageMiddleware.cs index 8ea3f113eb82..576f1a4e7b68 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageMiddleware.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageMiddleware.cs @@ -52,20 +52,9 @@ public DatabaseErrorPageMiddleware( ILoggerFactory loggerFactory, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; @@ -83,10 +72,7 @@ public DatabaseErrorPageMiddleware( /// A task that represents the asynchronous operation. public virtual async Task Invoke(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); try { diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointExtensions.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointExtensions.cs index fcc819b3d604..a085b7eb08f3 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointExtensions.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointExtensions.cs @@ -19,10 +19,7 @@ public static class MigrationsEndPointExtensions /// The same instance so that multiple calls can be chained. public static IApplicationBuilder UseMigrationsEndPoint(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMigrationsEndPoint(new MigrationsEndPointOptions()); } @@ -35,14 +32,8 @@ public static IApplicationBuilder UseMigrationsEndPoint(this IApplicationBuilder /// The same instance so that multiple calls can be chained. public static IApplicationBuilder UseMigrationsEndPoint(this IApplicationBuilder app, MigrationsEndPointOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointMiddleware.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointMiddleware.cs index a78e2fb80a80..1562bf7bd16f 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointMiddleware.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/src/MigrationsEndPointMiddleware.cs @@ -32,20 +32,9 @@ public MigrationsEndPointMiddleware( ILogger logger, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(options); _next = next; _logger = logger; @@ -59,10 +48,7 @@ public MigrationsEndPointMiddleware( /// A task that represents the asynchronous operation. public virtual Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Request.Path.Equals(_options.Path)) { diff --git a/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageExtensions.cs b/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageExtensions.cs index 39e1ecb24dd6..331d2d5eb8d7 100644 --- a/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageExtensions.cs +++ b/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageExtensions.cs @@ -21,10 +21,7 @@ public static class DeveloperExceptionPageExtensions /// public static IApplicationBuilder UseDeveloperExceptionPage(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); app.Properties["analysis.NextMiddlewareName"] = "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware"; return app.UseMiddleware(); @@ -43,15 +40,8 @@ public static IApplicationBuilder UseDeveloperExceptionPage( this IApplicationBuilder app, DeveloperExceptionPageOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); app.Properties["analysis.NextMiddlewareName"] = "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware"; return app.UseMiddleware(Options.Create(options)); diff --git a/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddlewareImpl.cs b/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddlewareImpl.cs index 1af140bb4787..91e74ef529a6 100644 --- a/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddlewareImpl.cs +++ b/src/Middleware/Diagnostics/src/DeveloperExceptionPage/DeveloperExceptionPageMiddlewareImpl.cs @@ -61,20 +61,9 @@ public DeveloperExceptionPageMiddlewareImpl( IOptions? jsonOptions = null, IProblemDetailsService? problemDetailsService = null) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (filters == null) - { - throw new ArgumentNullException(nameof(filters)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(filters); _next = next; _options = options.Value; diff --git a/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerExtensions.cs b/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerExtensions.cs index a0e77bd337dc..2cb6d10f77c5 100644 --- a/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerExtensions.cs +++ b/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerExtensions.cs @@ -24,10 +24,7 @@ public static class ExceptionHandlerExtensions /// public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return SetExceptionHandlerMiddleware(app, options: null); } @@ -41,10 +38,7 @@ public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder a /// public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, string errorHandlingPath) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseExceptionHandler(new ExceptionHandlerOptions { @@ -61,14 +55,8 @@ public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder a /// public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, Action configure) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(configure); var subAppBuilder = app.New(); configure(subAppBuilder); @@ -89,14 +77,8 @@ public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder a /// public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, ExceptionHandlerOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); var iOptions = Options.Create(options); return SetExceptionHandlerMiddleware(app, iOptions); diff --git a/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs b/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs index b026250629b3..ce758229b7d7 100644 --- a/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs +++ b/src/Middleware/Diagnostics/src/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs @@ -18,14 +18,8 @@ public static class ExceptionHandlerServiceCollectionExtensions /// public static IServiceCollection AddExceptionHandler(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); return services.Configure(configureOptions); } @@ -38,14 +32,8 @@ public static IServiceCollection AddExceptionHandler(this IServiceCollection ser /// public static IServiceCollection AddExceptionHandler(this IServiceCollection services, Action configureOptions) where TService : class { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions().Configure(configureOptions); return services; diff --git a/src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesExtensions.cs b/src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesExtensions.cs index f615da9112da..ca6bcdd840b8 100644 --- a/src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesExtensions.cs +++ b/src/Middleware/Diagnostics/src/StatusCodePage/StatusCodePagesExtensions.cs @@ -24,14 +24,8 @@ public static class StatusCodePagesExtensions /// public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app, StatusCodePagesOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } @@ -44,10 +38,7 @@ public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder ap /// public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -61,14 +52,8 @@ public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder ap /// public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app, Func handler) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(handler); return app.UseStatusCodePages(new StatusCodePagesOptions { @@ -86,10 +71,7 @@ public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder ap /// public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app, string contentType, string bodyFormat) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseStatusCodePages(context => { @@ -109,10 +91,7 @@ public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder ap /// public static IApplicationBuilder UseStatusCodePagesWithRedirects(this IApplicationBuilder app, string locationFormat) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); if (locationFormat.StartsWith('~')) { @@ -144,10 +123,7 @@ public static IApplicationBuilder UseStatusCodePagesWithRedirects(this IApplicat /// public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app, Action configuration) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); var builder = app.New(); configuration(builder); @@ -168,10 +144,7 @@ public static IApplicationBuilder UseStatusCodePagesWithReExecute( string pathFormat, string? queryFormat = null) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); // Only use this path if there's a global router (in the 'WebApplication' case). if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null) diff --git a/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageExtensions.cs b/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageExtensions.cs index 87f625de47f1..9902ad920600 100644 --- a/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageExtensions.cs +++ b/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageExtensions.cs @@ -20,14 +20,8 @@ public static class WelcomePageExtensions /// public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, WelcomePageOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } @@ -40,10 +34,7 @@ public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, W /// public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, PathString path) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseWelcomePage(new WelcomePageOptions { @@ -59,10 +50,7 @@ public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, P /// public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, string path) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseWelcomePage(new WelcomePageOptions { @@ -77,10 +65,7 @@ public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app, s /// public static IApplicationBuilder UseWelcomePage(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } diff --git a/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageMiddleware.cs b/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageMiddleware.cs index ddb64d89e3bf..120d71c80fb8 100644 --- a/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageMiddleware.cs +++ b/src/Middleware/Diagnostics/src/WelcomePage/WelcomePageMiddleware.cs @@ -23,15 +23,8 @@ public class WelcomePageMiddleware /// public WelcomePageMiddleware(RequestDelegate next, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; diff --git a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationApplicationBuilderExtensions.cs b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationApplicationBuilderExtensions.cs index 4e5899d639af..8dbd12a26eda 100644 --- a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationApplicationBuilderExtensions.cs +++ b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationApplicationBuilderExtensions.cs @@ -26,10 +26,7 @@ public static class HeaderPropagationApplicationBuilderExtensions /// A reference to the after the operation has completed. public static IApplicationBuilder UseHeaderPropagation(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); if (app.ApplicationServices.GetService() == null) { diff --git a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationHttpClientBuilderExtensions.cs b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationHttpClientBuilderExtensions.cs index 724bf8003b9a..013b92a3f5f6 100644 --- a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationHttpClientBuilderExtensions.cs +++ b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationHttpClientBuilderExtensions.cs @@ -21,10 +21,7 @@ public static class HeaderPropagationHttpClientBuilderExtensions /// The so that additional calls can be chained. public static IHttpClientBuilder AddHeaderPropagation(this IHttpClientBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.AddHeaderPropagation(); @@ -53,15 +50,8 @@ public static IHttpClientBuilder AddHeaderPropagation(this IHttpClientBuilder bu /// The so that additional calls can be chained. public static IHttpClientBuilder AddHeaderPropagation(this IHttpClientBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.AddHeaderPropagation(); diff --git a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs index 5cb9460a58eb..8259ef6a2973 100644 --- a/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs +++ b/src/Middleware/HeaderPropagation/src/DependencyInjection/HeaderPropagationServiceCollectionExtensions.cs @@ -19,10 +19,7 @@ public static class HeaderPropagationServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddHeaderPropagation(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); @@ -37,15 +34,8 @@ public static IServiceCollection AddHeaderPropagation(this IServiceCollection se /// The so that additional calls can be chained. public static IServiceCollection AddHeaderPropagation(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.AddHeaderPropagation(); diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationContext.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationContext.cs index 724e58717b88..598e72ce40ec 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationContext.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationContext.cs @@ -20,15 +20,8 @@ public readonly struct HeaderPropagationContext /// The header value present in the current request. public HeaderPropagationContext(HttpContext httpContext, string headerName, StringValues headerValue) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (headerName == null) - { - throw new ArgumentNullException(nameof(headerName)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(headerName); HttpContext = httpContext; HeaderName = headerName; diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationEntry.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationEntry.cs index 28f6a2779973..aaeb4e1a28c0 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationEntry.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationEntry.cs @@ -28,15 +28,8 @@ public HeaderPropagationEntry( string capturedHeaderName, Func? valueFilter) { - if (inboundHeaderName == null) - { - throw new ArgumentNullException(nameof(inboundHeaderName)); - } - - if (capturedHeaderName == null) - { - throw new ArgumentNullException(nameof(capturedHeaderName)); - } + ArgumentNullException.ThrowIfNull(inboundHeaderName); + ArgumentNullException.ThrowIfNull(capturedHeaderName); InboundHeaderName = inboundHeaderName; CapturedHeaderName = capturedHeaderName; diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationEntryCollection.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationEntryCollection.cs index 1d6e1f69e987..7a36f320b3df 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationEntryCollection.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationEntryCollection.cs @@ -19,10 +19,7 @@ public sealed class HeaderPropagationEntryCollection : CollectionThe header name to be propagated. public void Add(string headerName) { - if (headerName == null) - { - throw new ArgumentNullException(nameof(headerName)); - } + ArgumentNullException.ThrowIfNull(headerName); Add(new HeaderPropagationEntry(headerName, headerName, valueFilter: null)); } @@ -39,10 +36,7 @@ public void Add(string headerName) /// public void Add(string headerName, Func valueFilter) { - if (headerName == null) - { - throw new ArgumentNullException(nameof(headerName)); - } + ArgumentNullException.ThrowIfNull(headerName); Add(new HeaderPropagationEntry(headerName, headerName, valueFilter)); } @@ -59,15 +53,8 @@ public void Add(string headerName, Func /// public void Add(string inboundHeaderName, string outboundHeaderName) { - if (inboundHeaderName == null) - { - throw new ArgumentNullException(nameof(inboundHeaderName)); - } - - if (outboundHeaderName == null) - { - throw new ArgumentNullException(nameof(outboundHeaderName)); - } + ArgumentNullException.ThrowIfNull(inboundHeaderName); + ArgumentNullException.ThrowIfNull(outboundHeaderName); Add(new HeaderPropagationEntry(inboundHeaderName, outboundHeaderName, valueFilter: null)); } @@ -91,15 +78,8 @@ public void Add( string outboundHeaderName, Func valueFilter) { - if (inboundHeaderName == null) - { - throw new ArgumentNullException(nameof(inboundHeaderName)); - } - - if (outboundHeaderName == null) - { - throw new ArgumentNullException(nameof(outboundHeaderName)); - } + ArgumentNullException.ThrowIfNull(inboundHeaderName); + ArgumentNullException.ThrowIfNull(outboundHeaderName); Add(new HeaderPropagationEntry(inboundHeaderName, outboundHeaderName, valueFilter)); } diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntry.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntry.cs index 61de5f7badcc..1580c6b9c386 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntry.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntry.cs @@ -22,15 +22,8 @@ public HeaderPropagationMessageHandlerEntry( string capturedHeaderName, string outboundHeaderName) { - if (capturedHeaderName == null) - { - throw new ArgumentNullException(nameof(capturedHeaderName)); - } - - if (outboundHeaderName == null) - { - throw new ArgumentNullException(nameof(outboundHeaderName)); - } + ArgumentNullException.ThrowIfNull(capturedHeaderName); + ArgumentNullException.ThrowIfNull(outboundHeaderName); CapturedHeaderName = capturedHeaderName; OutboundHeaderName = outboundHeaderName; diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntryCollection.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntryCollection.cs index 612e17552a1e..eb1788a6b09b 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntryCollection.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationMessageHandlerEntryCollection.cs @@ -20,10 +20,7 @@ public sealed class HeaderPropagationMessageHandlerEntryCollection : Collection< /// public void Add(string headerName) { - if (headerName == null) - { - throw new ArgumentNullException(nameof(headerName)); - } + ArgumentNullException.ThrowIfNull(headerName); Add(new HeaderPropagationMessageHandlerEntry(headerName, headerName)); } @@ -40,15 +37,8 @@ public void Add(string headerName) /// public void Add(string capturedHeaderName, string outboundHeaderName) { - if (capturedHeaderName == null) - { - throw new ArgumentNullException(nameof(capturedHeaderName)); - } - - if (outboundHeaderName == null) - { - throw new ArgumentNullException(nameof(outboundHeaderName)); - } + ArgumentNullException.ThrowIfNull(capturedHeaderName); + ArgumentNullException.ThrowIfNull(outboundHeaderName); Add(new HeaderPropagationMessageHandlerEntry(capturedHeaderName, outboundHeaderName)); } diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationMiddleware.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationMiddleware.cs index 31ac52e4b9c5..60153b611916 100644 --- a/src/Middleware/HeaderPropagation/src/HeaderPropagationMiddleware.cs +++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationMiddleware.cs @@ -27,15 +27,13 @@ public class HeaderPropagationMiddleware /// public HeaderPropagationMiddleware(RequestDelegate next, IOptions options, HeaderPropagationValues values) { - _next = next ?? throw new ArgumentNullException(nameof(next)); + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(values); - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + _next = next; _options = options.Value; - - _values = values ?? throw new ArgumentNullException(nameof(values)); + _values = values; } /// diff --git a/src/Middleware/HealthChecks.EntityFrameworkCore/src/DbContextHealthCheck.cs b/src/Middleware/HealthChecks.EntityFrameworkCore/src/DbContextHealthCheck.cs index f890e9f38787..d5496ec9afe9 100644 --- a/src/Middleware/HealthChecks.EntityFrameworkCore/src/DbContextHealthCheck.cs +++ b/src/Middleware/HealthChecks.EntityFrameworkCore/src/DbContextHealthCheck.cs @@ -18,15 +18,8 @@ internal sealed class DbContextHealthCheck : IHealthCheck where TConte public DbContextHealthCheck(TContext dbContext, IOptionsMonitor> options) { - if (dbContext == null) - { - throw new ArgumentNullException(nameof(dbContext)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(dbContext); + ArgumentNullException.ThrowIfNull(options); _dbContext = dbContext; _options = options; @@ -34,10 +27,7 @@ public DbContextHealthCheck(TContext dbContext, IOptionsMonitor CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var options = _options.Get(context.Registration.Name); var testQuery = options.CustomTestQuery ?? DefaultTestQuery; diff --git a/src/Middleware/HealthChecks.EntityFrameworkCore/src/DependencyInjection/EntityFrameworkCoreHealthChecksBuilderExtensions.cs b/src/Middleware/HealthChecks.EntityFrameworkCore/src/DependencyInjection/EntityFrameworkCoreHealthChecksBuilderExtensions.cs index bfe5e7b11394..d7e88d4eb779 100644 --- a/src/Middleware/HealthChecks.EntityFrameworkCore/src/DependencyInjection/EntityFrameworkCoreHealthChecksBuilderExtensions.cs +++ b/src/Middleware/HealthChecks.EntityFrameworkCore/src/DependencyInjection/EntityFrameworkCoreHealthChecksBuilderExtensions.cs @@ -57,10 +57,7 @@ public static IHealthChecksBuilder AddDbContextCheck( Func>? customTestQuery = default) where TContext : DbContext { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); if (name == null) { diff --git a/src/Middleware/HealthChecks/src/Builder/HealthCheckApplicationBuilderExtensions.cs b/src/Middleware/HealthChecks/src/Builder/HealthCheckApplicationBuilderExtensions.cs index 4417856a390d..82ff980cb1a6 100644 --- a/src/Middleware/HealthChecks/src/Builder/HealthCheckApplicationBuilderExtensions.cs +++ b/src/Middleware/HealthChecks/src/Builder/HealthCheckApplicationBuilderExtensions.cs @@ -33,10 +33,7 @@ public static class HealthCheckApplicationBuilderExtensions /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); UseHealthChecksCore(app, path, port: null, Array.Empty()); return app; @@ -59,15 +56,8 @@ public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, HealthCheckOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); UseHealthChecksCore(app, path, port: null, new[] { Options.Create(options), }); return app; @@ -94,10 +84,7 @@ public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, int port) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); UseHealthChecksCore(app, path, port, Array.Empty()); return app; @@ -124,15 +111,8 @@ public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, string port) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (port == null) - { - throw new ArgumentNullException(nameof(port)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(port); if (!int.TryParse(port, out var portAsInt)) { @@ -162,15 +142,8 @@ public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, int port, HealthCheckOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); UseHealthChecksCore(app, path, port, new[] { Options.Create(options), }); return app; @@ -195,30 +168,21 @@ public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, /// public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app, PathString path, string port, HealthCheckOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); if (path == null) { throw new ArgumentNullException(nameof(path)); } - if (port == null) - { - throw new ArgumentNullException(nameof(port)); - } + ArgumentNullException.ThrowIfNull(port); if (!int.TryParse(port, out var portAsInt)) { throw new ArgumentException("The port must be a valid integer.", nameof(port)); } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); UseHealthChecksCore(app, path, portAsInt, new[] { Options.Create(options), }); return app; diff --git a/src/Middleware/HealthChecks/src/Builder/HealthCheckEndpointRouteBuilderExtensions.cs b/src/Middleware/HealthChecks/src/Builder/HealthCheckEndpointRouteBuilderExtensions.cs index 8a102fb19bc1..6e3c01498cd0 100644 --- a/src/Middleware/HealthChecks/src/Builder/HealthCheckEndpointRouteBuilderExtensions.cs +++ b/src/Middleware/HealthChecks/src/Builder/HealthCheckEndpointRouteBuilderExtensions.cs @@ -27,10 +27,7 @@ public static IEndpointConventionBuilder MapHealthChecks( this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); return MapHealthChecksCore(endpoints, pattern, null); } @@ -47,15 +44,8 @@ public static IEndpointConventionBuilder MapHealthChecks( [StringSyntax("Route")] string pattern, HealthCheckOptions options) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(options); return MapHealthChecksCore(endpoints, pattern, options); } diff --git a/src/Middleware/HealthChecks/src/HealthCheckMiddleware.cs b/src/Middleware/HealthChecks/src/HealthCheckMiddleware.cs index c6c6c94dabbf..5d76a34619eb 100644 --- a/src/Middleware/HealthChecks/src/HealthCheckMiddleware.cs +++ b/src/Middleware/HealthChecks/src/HealthCheckMiddleware.cs @@ -24,20 +24,9 @@ public HealthCheckMiddleware( IOptions healthCheckOptions, HealthCheckService healthCheckService) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (healthCheckOptions == null) - { - throw new ArgumentNullException(nameof(healthCheckOptions)); - } - - if (healthCheckService == null) - { - throw new ArgumentNullException(nameof(healthCheckService)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(healthCheckOptions); + ArgumentNullException.ThrowIfNull(healthCheckService); _next = next; _healthCheckOptions = healthCheckOptions.Value; @@ -51,10 +40,7 @@ public HealthCheckMiddleware( /// public async Task InvokeAsync(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); // Get results var result = await _healthCheckService.CheckHealthAsync(_healthCheckOptions.Predicate, httpContext.RequestAborted); diff --git a/src/Middleware/HostFiltering/src/HostFilteringBuilderExtensions.cs b/src/Middleware/HostFiltering/src/HostFilteringBuilderExtensions.cs index 344fc780fb8f..e43b1cbb6b26 100644 --- a/src/Middleware/HostFiltering/src/HostFilteringBuilderExtensions.cs +++ b/src/Middleware/HostFiltering/src/HostFilteringBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class HostFilteringBuilderExtensions /// The original . public static IApplicationBuilder UseHostFiltering(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); app.UseMiddleware(); diff --git a/src/Middleware/HostFiltering/src/HostFilteringServicesExtensions.cs b/src/Middleware/HostFiltering/src/HostFilteringServicesExtensions.cs index e47491207228..6ecc1a6a7796 100644 --- a/src/Middleware/HostFiltering/src/HostFilteringServicesExtensions.cs +++ b/src/Middleware/HostFiltering/src/HostFilteringServicesExtensions.cs @@ -19,14 +19,8 @@ public static class HostFilteringServicesExtensions /// public static IServiceCollection AddHostFiltering(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); return services; diff --git a/src/Middleware/HttpLogging/src/HttpLoggingBuilderExtensions.cs b/src/Middleware/HttpLogging/src/HttpLoggingBuilderExtensions.cs index 821289cf96ae..63d4a1ff1274 100644 --- a/src/Middleware/HttpLogging/src/HttpLoggingBuilderExtensions.cs +++ b/src/Middleware/HttpLogging/src/HttpLoggingBuilderExtensions.cs @@ -17,10 +17,7 @@ public static class HttpLoggingBuilderExtensions /// The . public static IApplicationBuilder UseHttpLogging(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); app.UseMiddleware(); return app; @@ -33,10 +30,7 @@ public static IApplicationBuilder UseHttpLogging(this IApplicationBuilder app) /// The . public static IApplicationBuilder UseW3CLogging(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); app.UseMiddleware(); return app; diff --git a/src/Middleware/HttpLogging/src/HttpLoggingMiddleware.cs b/src/Middleware/HttpLogging/src/HttpLoggingMiddleware.cs index d2417a3022eb..452c83c4dec1 100644 --- a/src/Middleware/HttpLogging/src/HttpLoggingMiddleware.cs +++ b/src/Middleware/HttpLogging/src/HttpLoggingMiddleware.cs @@ -28,18 +28,11 @@ internal sealed class HttpLoggingMiddleware /// public HttpLoggingMiddleware(RequestDelegate next, IOptionsMonitor options, ILogger logger) { - _next = next ?? throw new ArgumentNullException(nameof(next)); - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); + _next = next; _options = options; _logger = logger; } @@ -180,7 +173,7 @@ private async Task InvokeInternal(HttpContext context) if (ResponseHeadersNotYetWritten(responseBufferingStream, loggableUpgradeFeature)) { - // No body, not an upgradable request or request not upgraded, write headers here. + // No body, not an upgradable request or request not upgraded, write headers here. LogResponseHeaders(response, options, _logger); } diff --git a/src/Middleware/HttpLogging/src/HttpLoggingServicesExtensions.cs b/src/Middleware/HttpLogging/src/HttpLoggingServicesExtensions.cs index 3634893fc77b..077f8b19c1c4 100644 --- a/src/Middleware/HttpLogging/src/HttpLoggingServicesExtensions.cs +++ b/src/Middleware/HttpLogging/src/HttpLoggingServicesExtensions.cs @@ -18,14 +18,8 @@ public static class HttpLoggingServicesExtensions /// public static IServiceCollection AddHttpLogging(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); return services; @@ -39,14 +33,8 @@ public static IServiceCollection AddHttpLogging(this IServiceCollection services /// public static IServiceCollection AddW3CLogging(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.AddSingleton(); diff --git a/src/Middleware/HttpLogging/src/MediaTypeOptions.cs b/src/Middleware/HttpLogging/src/MediaTypeOptions.cs index e4a0d5de3b1e..48aa9deefe37 100644 --- a/src/Middleware/HttpLogging/src/MediaTypeOptions.cs +++ b/src/Middleware/HttpLogging/src/MediaTypeOptions.cs @@ -33,10 +33,7 @@ internal static MediaTypeOptions BuildDefaultMediaTypeOptions() internal void AddText(MediaTypeHeaderValue mediaType) { - if (mediaType == null) - { - throw new ArgumentNullException(nameof(mediaType)); - } + ArgumentNullException.ThrowIfNull(mediaType); mediaType.Encoding ??= Encoding.UTF8; @@ -52,10 +49,7 @@ internal void AddText(MediaTypeHeaderValue mediaType) /// The content type to add. public void AddText(string contentType) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); AddText(MediaTypeHeaderValue.Parse(contentType)); } @@ -67,15 +61,8 @@ public void AddText(string contentType) /// The encoding to use. public void AddText(string contentType, Encoding encoding) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(contentType); + ArgumentNullException.ThrowIfNull(encoding); var mediaType = MediaTypeHeaderValue.Parse(contentType); mediaType.Encoding = encoding; diff --git a/src/Middleware/HttpLogging/src/W3CLoggingMiddleware.cs b/src/Middleware/HttpLogging/src/W3CLoggingMiddleware.cs index f4cd17c5b2a7..bd041087e928 100644 --- a/src/Middleware/HttpLogging/src/W3CLoggingMiddleware.cs +++ b/src/Middleware/HttpLogging/src/W3CLoggingMiddleware.cs @@ -52,20 +52,9 @@ internal sealed class W3CLoggingMiddleware /// public W3CLoggingMiddleware(RequestDelegate next, IOptionsMonitor options, W3CLogger w3cLogger) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (w3cLogger == null) - { - throw new ArgumentNullException(nameof(w3cLogger)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(w3cLogger); _next = next; _options = options; diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingBuilderExtensions.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingBuilderExtensions.cs index 8bbb9453752b..66617ec4576b 100644 --- a/src/Middleware/HttpOverrides/src/CertificateForwardingBuilderExtensions.cs +++ b/src/Middleware/HttpOverrides/src/CertificateForwardingBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class CertificateForwardingBuilderExtensions /// public static IApplicationBuilder UseCertificateForwarding(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingMiddleware.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingMiddleware.cs index 653cef4612f3..532ff6183ff9 100644 --- a/src/Middleware/HttpOverrides/src/CertificateForwardingMiddleware.cs +++ b/src/Middleware/HttpOverrides/src/CertificateForwardingMiddleware.cs @@ -29,18 +29,11 @@ public CertificateForwardingMiddleware( ILoggerFactory loggerFactory, IOptions options) { - _next = next ?? throw new ArgumentNullException(nameof(next)); - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); + _next = next; _options = options.Value; _logger = loggerFactory.CreateLogger(); } diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingServiceExtensions.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingServiceExtensions.cs index 9deee9de5035..8c6e98506ab0 100644 --- a/src/Middleware/HttpOverrides/src/CertificateForwardingServiceExtensions.cs +++ b/src/Middleware/HttpOverrides/src/CertificateForwardingServiceExtensions.cs @@ -20,15 +20,8 @@ public static IServiceCollection AddCertificateForwarding( this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configure); services.AddOptions().Validate(o => !string.IsNullOrEmpty(o.CertificateHeader), "CertificateForwarderOptions.CertificateHeader cannot be null or empty."); return services.Configure(configure); diff --git a/src/Middleware/HttpOverrides/src/ForwardedHeadersExtensions.cs b/src/Middleware/HttpOverrides/src/ForwardedHeadersExtensions.cs index 5820da42261b..06d40a00c9c4 100644 --- a/src/Middleware/HttpOverrides/src/ForwardedHeadersExtensions.cs +++ b/src/Middleware/HttpOverrides/src/ForwardedHeadersExtensions.cs @@ -24,10 +24,7 @@ public static class ForwardedHeadersExtensions /// A reference to after the operation has completed. public static IApplicationBuilder UseForwardedHeaders(this IApplicationBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); // Don't add more than one instance of this middleware to the pipeline using the options from the DI container. // Doing so could cause a request to be processed multiple times and the ForwardLimit to be exceeded. @@ -52,14 +49,8 @@ public static IApplicationBuilder UseForwardedHeaders(this IApplicationBuilder b /// A reference to after the operation has completed. public static IApplicationBuilder UseForwardedHeaders(this IApplicationBuilder builder, ForwardedHeadersOptions options) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(options); return builder.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs b/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs index a430140b6603..da126640af9e 100644 --- a/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs +++ b/src/Middleware/HttpOverrides/src/ForwardedHeadersMiddleware.cs @@ -70,18 +70,9 @@ static ForwardedHeadersMiddleware() /// The for configuring the middleware. public ForwardedHeadersMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); // Make sure required options is not null or whitespace EnsureOptionNotNullorWhitespace(options.Value.ForwardedForHeaderName, nameof(options.Value.ForwardedForHeaderName)); diff --git a/src/Middleware/HttpOverrides/src/HttpMethodOverrideExtensions.cs b/src/Middleware/HttpOverrides/src/HttpMethodOverrideExtensions.cs index ec1e229e3df9..e419ca9bdb9d 100644 --- a/src/Middleware/HttpOverrides/src/HttpMethodOverrideExtensions.cs +++ b/src/Middleware/HttpOverrides/src/HttpMethodOverrideExtensions.cs @@ -19,10 +19,7 @@ public static class HttpMethodOverrideExtensions /// The instance this method extends. public static IApplicationBuilder UseHttpMethodOverride(this IApplicationBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return builder.UseMiddleware(); } @@ -37,14 +34,8 @@ public static IApplicationBuilder UseHttpMethodOverride(this IApplicationBuilder /// public static IApplicationBuilder UseHttpMethodOverride(this IApplicationBuilder builder, HttpMethodOverrideOptions options) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(options); return builder.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/HttpOverrides/src/HttpMethodOverrideMiddleware.cs b/src/Middleware/HttpOverrides/src/HttpMethodOverrideMiddleware.cs index a26fc887cca2..234aafb07e63 100644 --- a/src/Middleware/HttpOverrides/src/HttpMethodOverrideMiddleware.cs +++ b/src/Middleware/HttpOverrides/src/HttpMethodOverrideMiddleware.cs @@ -23,14 +23,8 @@ public class HttpMethodOverrideMiddleware /// The for configuring the middleware. public HttpMethodOverrideMiddleware(RequestDelegate next, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; } diff --git a/src/Middleware/HttpsPolicy/src/HstsBuilderExtensions.cs b/src/Middleware/HttpsPolicy/src/HstsBuilderExtensions.cs index b29251ae017c..4a4118dc5765 100644 --- a/src/Middleware/HttpsPolicy/src/HstsBuilderExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HstsBuilderExtensions.cs @@ -16,10 +16,7 @@ public static class HstsBuilderExtensions /// The instance this method extends. public static IApplicationBuilder UseHsts(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } diff --git a/src/Middleware/HttpsPolicy/src/HstsMiddleware.cs b/src/Middleware/HttpsPolicy/src/HstsMiddleware.cs index 71d1cd6fb299..c94601faa970 100644 --- a/src/Middleware/HttpsPolicy/src/HstsMiddleware.cs +++ b/src/Middleware/HttpsPolicy/src/HstsMiddleware.cs @@ -32,10 +32,7 @@ public class HstsMiddleware /// public HstsMiddleware(RequestDelegate next, IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); _next = next ?? throw new ArgumentNullException(nameof(next)); diff --git a/src/Middleware/HttpsPolicy/src/HstsServicesExtensions.cs b/src/Middleware/HttpsPolicy/src/HstsServicesExtensions.cs index 5ccd753c80e2..f4c55fc55e60 100644 --- a/src/Middleware/HttpsPolicy/src/HstsServicesExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HstsServicesExtensions.cs @@ -19,14 +19,8 @@ public static class HstsServicesExtensions /// public static IServiceCollection AddHsts(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); return services; diff --git a/src/Middleware/HttpsPolicy/src/HttpsRedirectionBuilderExtensions.cs b/src/Middleware/HttpsPolicy/src/HttpsRedirectionBuilderExtensions.cs index f8b190c91a71..e86dd60a99c6 100644 --- a/src/Middleware/HttpsPolicy/src/HttpsRedirectionBuilderExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HttpsRedirectionBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class HttpsPolicyBuilderExtensions /// The for HttpsRedirection. public static IApplicationBuilder UseHttpsRedirection(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); var serverAddressFeature = app.ServerFeatures.Get(); if (serverAddressFeature != null) diff --git a/src/Middleware/HttpsPolicy/src/HttpsRedirectionMiddleware.cs b/src/Middleware/HttpsPolicy/src/HttpsRedirectionMiddleware.cs index ebc479192b1e..a7c22d066f00 100644 --- a/src/Middleware/HttpsPolicy/src/HttpsRedirectionMiddleware.cs +++ b/src/Middleware/HttpsPolicy/src/HttpsRedirectionMiddleware.cs @@ -35,13 +35,13 @@ public class HttpsRedirectionMiddleware /// public HttpsRedirectionMiddleware(RequestDelegate next, IOptions options, IConfiguration config, ILoggerFactory loggerFactory) { - _next = next ?? throw new ArgumentNullException(nameof(next)); - _config = config ?? throw new ArgumentNullException(nameof(config)); + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(config); + + _next = next; + _config = config; - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } var httpsRedirectionOptions = options.Value; if (httpsRedirectionOptions.HttpsPort.HasValue) { diff --git a/src/Middleware/HttpsPolicy/src/HttpsRedirectionServicesExtensions.cs b/src/Middleware/HttpsPolicy/src/HttpsRedirectionServicesExtensions.cs index 975c0eb20b3c..29a5a15eb8bb 100644 --- a/src/Middleware/HttpsPolicy/src/HttpsRedirectionServicesExtensions.cs +++ b/src/Middleware/HttpsPolicy/src/HttpsRedirectionServicesExtensions.cs @@ -19,14 +19,8 @@ public static class HttpsRedirectionServicesExtensions /// public static IServiceCollection AddHttpsRedirection(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); return services; } diff --git a/src/Middleware/Localization.Routing/src/RouteDataRequestCultureProvider.cs b/src/Middleware/Localization.Routing/src/RouteDataRequestCultureProvider.cs index 78775fadae21..49e571578790 100644 --- a/src/Middleware/Localization.Routing/src/RouteDataRequestCultureProvider.cs +++ b/src/Middleware/Localization.Routing/src/RouteDataRequestCultureProvider.cs @@ -27,10 +27,7 @@ public class RouteDataRequestCultureProvider : RequestCultureProvider /// public override Task DetermineProviderCultureResult(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); string? culture = null; string? uiCulture = null; diff --git a/src/Middleware/Localization/src/AcceptLanguageHeaderRequestCultureProvider.cs b/src/Middleware/Localization/src/AcceptLanguageHeaderRequestCultureProvider.cs index 41a526bae05b..6995c7445b9d 100644 --- a/src/Middleware/Localization/src/AcceptLanguageHeaderRequestCultureProvider.cs +++ b/src/Middleware/Localization/src/AcceptLanguageHeaderRequestCultureProvider.cs @@ -22,10 +22,7 @@ public class AcceptLanguageHeaderRequestCultureProvider : RequestCultureProvider /// public override Task DetermineProviderCultureResult(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var acceptLanguageHeader = httpContext.Request.GetTypedHeaders().AcceptLanguage; diff --git a/src/Middleware/Localization/src/ApplicationBuilderExtensions.cs b/src/Middleware/Localization/src/ApplicationBuilderExtensions.cs index 457a0a587999..68f3008d77c6 100644 --- a/src/Middleware/Localization/src/ApplicationBuilderExtensions.cs +++ b/src/Middleware/Localization/src/ApplicationBuilderExtensions.cs @@ -19,10 +19,7 @@ public static class ApplicationBuilderExtensions /// The . public static IApplicationBuilder UseRequestLocalization(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -38,15 +35,8 @@ public static IApplicationBuilder UseRequestLocalization( this IApplicationBuilder app, RequestLocalizationOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } @@ -65,15 +55,8 @@ public static IApplicationBuilder UseRequestLocalization( this IApplicationBuilder app, Action optionsAction) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (optionsAction == null) - { - throw new ArgumentNullException(nameof(optionsAction)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(optionsAction); var options = new RequestLocalizationOptions(); optionsAction.Invoke(options); @@ -95,15 +78,8 @@ public static IApplicationBuilder UseRequestLocalization( this IApplicationBuilder app, params string[] cultures) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (cultures == null) - { - throw new ArgumentNullException(nameof(cultures)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(cultures); if (cultures.Length == 0) { diff --git a/src/Middleware/Localization/src/CookieRequestCultureProvider.cs b/src/Middleware/Localization/src/CookieRequestCultureProvider.cs index bc5b8f893326..d42efdba75e5 100644 --- a/src/Middleware/Localization/src/CookieRequestCultureProvider.cs +++ b/src/Middleware/Localization/src/CookieRequestCultureProvider.cs @@ -28,10 +28,7 @@ public class CookieRequestCultureProvider : RequestCultureProvider /// public override Task DetermineProviderCultureResult(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var cookie = httpContext.Request.Cookies[CookieName]; @@ -52,10 +49,7 @@ public class CookieRequestCultureProvider : RequestCultureProvider /// The cookie value. public static string MakeCookieValue(RequestCulture requestCulture) { - if (requestCulture == null) - { - throw new ArgumentNullException(nameof(requestCulture)); - } + ArgumentNullException.ThrowIfNull(requestCulture); return string.Join(_cookieSeparator, $"{_culturePrefix}{requestCulture.Culture.Name}", diff --git a/src/Middleware/Localization/src/CustomRequestCultureProvider.cs b/src/Middleware/Localization/src/CustomRequestCultureProvider.cs index c7f83bb34cc2..b3c9f12eb408 100644 --- a/src/Middleware/Localization/src/CustomRequestCultureProvider.cs +++ b/src/Middleware/Localization/src/CustomRequestCultureProvider.cs @@ -18,10 +18,7 @@ public class CustomRequestCultureProvider : RequestCultureProvider /// The provider delegate. public CustomRequestCultureProvider(Func> provider) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(provider); _provider = provider; } @@ -29,10 +26,7 @@ public CustomRequestCultureProvider(Func public override Task DetermineProviderCultureResult(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); return _provider(httpContext); } diff --git a/src/Middleware/Localization/src/QueryStringRequestCultureProvider.cs b/src/Middleware/Localization/src/QueryStringRequestCultureProvider.cs index 9e257c0f51b6..0ec41289e01a 100644 --- a/src/Middleware/Localization/src/QueryStringRequestCultureProvider.cs +++ b/src/Middleware/Localization/src/QueryStringRequestCultureProvider.cs @@ -26,10 +26,7 @@ public class QueryStringRequestCultureProvider : RequestCultureProvider /// public override Task DetermineProviderCultureResult(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var request = httpContext.Request; if (!request.QueryString.HasValue) diff --git a/src/Middleware/Localization/src/RequestCulture.cs b/src/Middleware/Localization/src/RequestCulture.cs index a08f9bb796b7..af6387f28ae9 100644 --- a/src/Middleware/Localization/src/RequestCulture.cs +++ b/src/Middleware/Localization/src/RequestCulture.cs @@ -49,15 +49,8 @@ public RequestCulture(string culture, string uiCulture) /// The for the request to be used for text, i.e. language. public RequestCulture(CultureInfo culture, CultureInfo uiCulture) { - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } - - if (uiCulture == null) - { - throw new ArgumentNullException(nameof(uiCulture)); - } + ArgumentNullException.ThrowIfNull(culture); + ArgumentNullException.ThrowIfNull(uiCulture); Culture = culture; UICulture = uiCulture; diff --git a/src/Middleware/Localization/src/RequestCultureFeature.cs b/src/Middleware/Localization/src/RequestCultureFeature.cs index 1b6b57f9988d..9579ea92f7c1 100644 --- a/src/Middleware/Localization/src/RequestCultureFeature.cs +++ b/src/Middleware/Localization/src/RequestCultureFeature.cs @@ -15,10 +15,7 @@ public class RequestCultureFeature : IRequestCultureFeature /// The . public RequestCultureFeature(RequestCulture requestCulture, IRequestCultureProvider? provider) { - if (requestCulture == null) - { - throw new ArgumentNullException(nameof(requestCulture)); - } + ArgumentNullException.ThrowIfNull(requestCulture); RequestCulture = requestCulture; Provider = provider; diff --git a/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs b/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs index af03b0deeae2..a4b099da6a9a 100644 --- a/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs +++ b/src/Middleware/Localization/src/RequestLocalizationMiddleware.cs @@ -32,10 +32,7 @@ public class RequestLocalizationMiddleware /// . public RequestLocalizationMiddleware(RequestDelegate next, IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); _next = next ?? throw new ArgumentNullException(nameof(next)); _logger = loggerFactory?.CreateLogger() ?? throw new ArgumentNullException(nameof(loggerFactory)); @@ -49,10 +46,7 @@ public RequestLocalizationMiddleware(RequestDelegate next, IOptionsA that completes when the middleware has completed processing. public async Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var requestCulture = _options.DefaultRequestCulture; diff --git a/src/Middleware/Localization/src/RequestLocalizationOptions.cs b/src/Middleware/Localization/src/RequestLocalizationOptions.cs index 5de0b6c22545..71fa3f0f45ed 100644 --- a/src/Middleware/Localization/src/RequestLocalizationOptions.cs +++ b/src/Middleware/Localization/src/RequestLocalizationOptions.cs @@ -45,10 +45,7 @@ public RequestCulture DefaultRequestCulture } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _defaultRequestCulture = value; } diff --git a/src/Middleware/Localization/src/RequestLocalizationOptionsExtensions.cs b/src/Middleware/Localization/src/RequestLocalizationOptionsExtensions.cs index 93a94b0107a4..c01e6f596e5f 100644 --- a/src/Middleware/Localization/src/RequestLocalizationOptionsExtensions.cs +++ b/src/Middleware/Localization/src/RequestLocalizationOptionsExtensions.cs @@ -21,15 +21,8 @@ public static RequestLocalizationOptions AddInitialRequestCultureProvider( this RequestLocalizationOptions requestLocalizationOptions, RequestCultureProvider requestCultureProvider) { - if (requestLocalizationOptions == null) - { - throw new ArgumentNullException(nameof(requestLocalizationOptions)); - } - - if (requestCultureProvider == null) - { - throw new ArgumentNullException(nameof(requestCultureProvider)); - } + ArgumentNullException.ThrowIfNull(requestLocalizationOptions); + ArgumentNullException.ThrowIfNull(requestCultureProvider); requestLocalizationOptions.RequestCultureProviders.Insert(0, requestCultureProvider); diff --git a/src/Middleware/Localization/src/RequestLocalizationServiceCollectionExtensions.cs b/src/Middleware/Localization/src/RequestLocalizationServiceCollectionExtensions.cs index 565e2c8a0216..e20f68fe2a88 100644 --- a/src/Middleware/Localization/src/RequestLocalizationServiceCollectionExtensions.cs +++ b/src/Middleware/Localization/src/RequestLocalizationServiceCollectionExtensions.cs @@ -18,14 +18,8 @@ public static class RequestLocalizationServiceCollectionExtensions /// The . public static IServiceCollection AddRequestLocalization(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); return services.Configure(configureOptions); } @@ -38,14 +32,8 @@ public static IServiceCollection AddRequestLocalization(this IServiceCollection /// The . public static IServiceCollection AddRequestLocalization(this IServiceCollection services, Action configureOptions) where TService : class { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions().Configure(configureOptions); return services; diff --git a/src/Middleware/MiddlewareAnalysis/src/AnalysisServiceCollectionExtensions.cs b/src/Middleware/MiddlewareAnalysis/src/AnalysisServiceCollectionExtensions.cs index 4df0eae5d791..4ce137e7944c 100644 --- a/src/Middleware/MiddlewareAnalysis/src/AnalysisServiceCollectionExtensions.cs +++ b/src/Middleware/MiddlewareAnalysis/src/AnalysisServiceCollectionExtensions.cs @@ -20,10 +20,7 @@ public static class AnalysisServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddMiddlewareAnalysis(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); // Prevent registering the same implementation of IStartupFilter (AnalysisStartupFilter) multiple times. // But allow multiple registrations of different implementation types. diff --git a/src/Middleware/OutputCaching/src/Streams/SegmentWriteStream.cs b/src/Middleware/OutputCaching/src/Streams/SegmentWriteStream.cs index cdbf680a1573..847cf645bc3a 100644 --- a/src/Middleware/OutputCaching/src/Streams/SegmentWriteStream.cs +++ b/src/Middleware/OutputCaching/src/Streams/SegmentWriteStream.cs @@ -101,7 +101,7 @@ public override void Flush() { if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } } @@ -125,7 +125,7 @@ public override void Write(byte[] buffer, int offset, int count) ValidateBufferArguments(buffer, offset, count); if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } Write(buffer.AsSpan(offset, count)); @@ -165,7 +165,7 @@ public override void WriteByte(byte value) { if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } if ((int)_bufferStream.Length == _segmentSize) diff --git a/src/Middleware/RateLimiting/src/RateLimiterEndpointConventionBuilderExtensions.cs b/src/Middleware/RateLimiting/src/RateLimiterEndpointConventionBuilderExtensions.cs index 1a5fb0e180bf..3fb4d423e047 100644 --- a/src/Middleware/RateLimiting/src/RateLimiterEndpointConventionBuilderExtensions.cs +++ b/src/Middleware/RateLimiting/src/RateLimiterEndpointConventionBuilderExtensions.cs @@ -19,7 +19,6 @@ public static class RateLimiterEndpointConventionBuilderExtensions public static TBuilder RequireRateLimiting(this TBuilder builder, string policyName) where TBuilder : IEndpointConventionBuilder { ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(policyName); builder.Add(endpointBuilder => @@ -39,7 +38,6 @@ public static TBuilder RequireRateLimiting(this TBuilder builder, stri public static TBuilder RequireRateLimiting(this TBuilder builder, IRateLimiterPolicy policy) where TBuilder : IEndpointConventionBuilder { ArgumentNullException.ThrowIfNull(builder); - ArgumentNullException.ThrowIfNull(policy); builder.Add(endpointBuilder => diff --git a/src/Middleware/RequestDecompression/src/DefaultRequestDecompressionProvider.cs b/src/Middleware/RequestDecompression/src/DefaultRequestDecompressionProvider.cs index 3178fcc5d288..7feff1789d22 100644 --- a/src/Middleware/RequestDecompression/src/DefaultRequestDecompressionProvider.cs +++ b/src/Middleware/RequestDecompression/src/DefaultRequestDecompressionProvider.cs @@ -19,15 +19,8 @@ public DefaultRequestDecompressionProvider( ILogger logger, IOptions options) { - if (logger is null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(options); _logger = logger; _providers = options.Value.DecompressionProviders; @@ -83,7 +76,7 @@ public static void DecompressingWith(ILogger logger, string contentEncoding) DecompressingWithCore(logger, contentEncoding.ToLowerInvariant()); } } - + [LoggerMessage(4, LogLevel.Debug, "The request will be decompressed with '{ContentEncoding}'.", EventName = "DecompressingWith", SkipEnabledCheck = true)] private static partial void DecompressingWithCore(ILogger logger, string contentEncoding); } diff --git a/src/Middleware/RequestDecompression/src/RequestDecompressionBuilderExtensions.cs b/src/Middleware/RequestDecompression/src/RequestDecompressionBuilderExtensions.cs index c67d2bdfd1d0..f81517a92441 100644 --- a/src/Middleware/RequestDecompression/src/RequestDecompressionBuilderExtensions.cs +++ b/src/Middleware/RequestDecompression/src/RequestDecompressionBuilderExtensions.cs @@ -16,10 +16,7 @@ public static class RequestDecompressionBuilderExtensions /// The instance this method extends. public static IApplicationBuilder UseRequestDecompression(this IApplicationBuilder builder) { - if (builder is null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return builder.UseMiddleware(); } diff --git a/src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs b/src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs index 253b1d238884..bd5f1b80b4d8 100644 --- a/src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs +++ b/src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs @@ -29,20 +29,9 @@ public RequestDecompressionMiddleware( ILogger logger, IRequestDecompressionProvider provider) { - if (next is null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (logger is null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (provider is null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(provider); _next = next; _logger = logger; diff --git a/src/Middleware/RequestDecompression/src/RequestDecompressionServiceExtensions.cs b/src/Middleware/RequestDecompression/src/RequestDecompressionServiceExtensions.cs index 7996ef88a93a..ce4e9e518596 100644 --- a/src/Middleware/RequestDecompression/src/RequestDecompressionServiceExtensions.cs +++ b/src/Middleware/RequestDecompression/src/RequestDecompressionServiceExtensions.cs @@ -18,10 +18,7 @@ public static class RequestDecompressionServiceExtensions /// The . public static IServiceCollection AddRequestDecompression(this IServiceCollection services) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); return services; @@ -35,15 +32,8 @@ public static IServiceCollection AddRequestDecompression(this IServiceCollection /// The . public static IServiceCollection AddRequestDecompression(this IServiceCollection services, Action configureOptions) { - if (services is null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions is null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.TryAddSingleton(); diff --git a/src/Middleware/RequestDecompression/src/SizeLimitedStream.cs b/src/Middleware/RequestDecompression/src/SizeLimitedStream.cs index 2c53bd73077d..976b3e398787 100644 --- a/src/Middleware/RequestDecompression/src/SizeLimitedStream.cs +++ b/src/Middleware/RequestDecompression/src/SizeLimitedStream.cs @@ -12,10 +12,7 @@ internal sealed class SizeLimitedStream : Stream public SizeLimitedStream(Stream innerStream, long? sizeLimit) { - if (innerStream is null) - { - throw new ArgumentNullException(nameof(innerStream)); - } + ArgumentNullException.ThrowIfNull(innerStream); _innerStream = innerStream; _sizeLimit = sizeLimit; diff --git a/src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs b/src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs index 21cfeb80baa1..2d7164da5fbf 100644 --- a/src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs +++ b/src/Middleware/ResponseCaching/src/CacheEntry/CachedResponseBody.cs @@ -19,10 +19,7 @@ public CachedResponseBody(List segments, long length) public async Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); foreach (var segment in Segments) { diff --git a/src/Middleware/ResponseCaching/src/ResponseCachingExtensions.cs b/src/Middleware/ResponseCaching/src/ResponseCachingExtensions.cs index 838f9af8ace5..0476ee9af76d 100644 --- a/src/Middleware/ResponseCaching/src/ResponseCachingExtensions.cs +++ b/src/Middleware/ResponseCaching/src/ResponseCachingExtensions.cs @@ -16,10 +16,7 @@ public static class ResponseCachingExtensions /// The . public static IApplicationBuilder UseResponseCaching(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } diff --git a/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs b/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs index 957f6faae6e7..54458ae19cf5 100644 --- a/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs +++ b/src/Middleware/ResponseCaching/src/ResponseCachingKeyProvider.cs @@ -21,14 +21,8 @@ internal sealed class ResponseCachingKeyProvider : IResponseCachingKeyProvider internal ResponseCachingKeyProvider(ObjectPoolProvider poolProvider, IOptions options) { - if (poolProvider == null) - { - throw new ArgumentNullException(nameof(poolProvider)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(poolProvider); + ArgumentNullException.ThrowIfNull(options); _builderPool = poolProvider.CreateStringBuilderPool(); _options = options.Value; @@ -42,10 +36,7 @@ public IEnumerable CreateLookupVaryByKeys(ResponseCachingContext context // GETSCHEMEHOST:PORT/PATHBASE/PATH public string CreateBaseKey(ResponseCachingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var request = context.HttpContext.Request; var builder = _builderPool.Get(); @@ -83,10 +74,7 @@ public string CreateBaseKey(ResponseCachingContext context) // BaseKeyHHeaderName=HeaderValueQQueryName=QueryValue1QueryValue2 public string CreateStorageVaryByKey(ResponseCachingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var varyByRules = context.CachedVaryByRules; if (varyByRules == null) diff --git a/src/Middleware/ResponseCaching/src/ResponseCachingMiddleware.cs b/src/Middleware/ResponseCaching/src/ResponseCachingMiddleware.cs index 24d0e9bab3b1..4b7de0ad9aa0 100644 --- a/src/Middleware/ResponseCaching/src/ResponseCachingMiddleware.cs +++ b/src/Middleware/ResponseCaching/src/ResponseCachingMiddleware.cs @@ -62,30 +62,12 @@ internal ResponseCachingMiddleware( IResponseCache cache, IResponseCachingKeyProvider keyProvider) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - if (policyProvider == null) - { - throw new ArgumentNullException(nameof(policyProvider)); - } - if (cache == null) - { - throw new ArgumentNullException(nameof(cache)); - } - if (keyProvider == null) - { - throw new ArgumentNullException(nameof(keyProvider)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(policyProvider); + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(keyProvider); _next = next; _options = options.Value; diff --git a/src/Middleware/ResponseCaching/src/ResponseCachingServicesExtensions.cs b/src/Middleware/ResponseCaching/src/ResponseCachingServicesExtensions.cs index 5474d55c5b90..482465df8f84 100644 --- a/src/Middleware/ResponseCaching/src/ResponseCachingServicesExtensions.cs +++ b/src/Middleware/ResponseCaching/src/ResponseCachingServicesExtensions.cs @@ -19,10 +19,7 @@ public static class ResponseCachingServicesExtensions /// public static IServiceCollection AddResponseCaching(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); @@ -37,14 +34,8 @@ public static IServiceCollection AddResponseCaching(this IServiceCollection serv /// public static IServiceCollection AddResponseCaching(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.AddResponseCaching(); diff --git a/src/Middleware/ResponseCaching/src/Streams/SegmentWriteStream.cs b/src/Middleware/ResponseCaching/src/Streams/SegmentWriteStream.cs index 60079b0f3a45..11e31dbec623 100644 --- a/src/Middleware/ResponseCaching/src/Streams/SegmentWriteStream.cs +++ b/src/Middleware/ResponseCaching/src/Streams/SegmentWriteStream.cs @@ -101,7 +101,7 @@ public override void Flush() { if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } } @@ -125,7 +125,7 @@ public override void Write(byte[] buffer, int offset, int count) ValidateBufferArguments(buffer, offset, count); if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } Write(buffer.AsSpan(offset, count)); @@ -165,7 +165,7 @@ public override void WriteByte(byte value) { if (!CanWrite) { - throw new ObjectDisposedException("The stream has been closed for writing."); + throw new ObjectDisposedException(nameof(SegmentWriteStream), "The stream has been closed for writing."); } if ((int)_bufferStream.Length == _segmentSize) diff --git a/src/Middleware/ResponseCaching/test/TestUtils.cs b/src/Middleware/ResponseCaching/test/TestUtils.cs index 08ae92d6eb70..3a4b5584a759 100644 --- a/src/Middleware/ResponseCaching/test/TestUtils.cs +++ b/src/Middleware/ResponseCaching/test/TestUtils.cs @@ -262,15 +262,8 @@ internal static class HttpResponseWritingExtensions { internal static void Write(this HttpResponse response, string text) { - if (response == null) - { - throw new ArgumentNullException(nameof(response)); - } - - if (text == null) - { - throw new ArgumentNullException(nameof(text)); - } + ArgumentNullException.ThrowIfNull(response); + ArgumentNullException.ThrowIfNull(text); byte[] data = Encoding.UTF8.GetBytes(text); response.Body.Write(data, 0, data.Length); diff --git a/src/Middleware/ResponseCompression/src/BrotliCompressionProvider.cs b/src/Middleware/ResponseCompression/src/BrotliCompressionProvider.cs index b586cf95344e..5b4244c48dc0 100644 --- a/src/Middleware/ResponseCompression/src/BrotliCompressionProvider.cs +++ b/src/Middleware/ResponseCompression/src/BrotliCompressionProvider.cs @@ -17,10 +17,7 @@ public class BrotliCompressionProvider : ICompressionProvider /// The options for this instance. public BrotliCompressionProvider(IOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); Options = options.Value; } diff --git a/src/Middleware/ResponseCompression/src/CompressionProviderCollection.cs b/src/Middleware/ResponseCompression/src/CompressionProviderCollection.cs index 1b1f80aeb292..ff592ae7f8be 100644 --- a/src/Middleware/ResponseCompression/src/CompressionProviderCollection.cs +++ b/src/Middleware/ResponseCompression/src/CompressionProviderCollection.cs @@ -32,10 +32,7 @@ public class CompressionProviderCollection : Collection /// public void Add([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type providerType) { - if (providerType == null) - { - throw new ArgumentNullException(nameof(providerType)); - } + ArgumentNullException.ThrowIfNull(providerType); if (!typeof(ICompressionProvider).IsAssignableFrom(providerType)) { diff --git a/src/Middleware/ResponseCompression/src/CompressionProviderFactory.cs b/src/Middleware/ResponseCompression/src/CompressionProviderFactory.cs index d39aa9e6aee4..47dbff68cbd1 100644 --- a/src/Middleware/ResponseCompression/src/CompressionProviderFactory.cs +++ b/src/Middleware/ResponseCompression/src/CompressionProviderFactory.cs @@ -22,10 +22,7 @@ public CompressionProviderFactory([DynamicallyAccessedMembers(DynamicallyAccesse public ICompressionProvider CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); return (ICompressionProvider)ActivatorUtilities.CreateInstance(serviceProvider, ProviderType, Type.EmptyTypes); } diff --git a/src/Middleware/ResponseCompression/src/GzipCompressionProvider.cs b/src/Middleware/ResponseCompression/src/GzipCompressionProvider.cs index f20f92885f40..b0c83e94ce4f 100644 --- a/src/Middleware/ResponseCompression/src/GzipCompressionProvider.cs +++ b/src/Middleware/ResponseCompression/src/GzipCompressionProvider.cs @@ -17,10 +17,7 @@ public class GzipCompressionProvider : ICompressionProvider /// The options for this instance. public GzipCompressionProvider(IOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); Options = options.Value; } diff --git a/src/Middleware/ResponseCompression/src/ResponseCompressionBuilderExtensions.cs b/src/Middleware/ResponseCompression/src/ResponseCompressionBuilderExtensions.cs index ccec41fdaf7b..61cacad12df8 100644 --- a/src/Middleware/ResponseCompression/src/ResponseCompressionBuilderExtensions.cs +++ b/src/Middleware/ResponseCompression/src/ResponseCompressionBuilderExtensions.cs @@ -16,10 +16,7 @@ public static class ResponseCompressionBuilderExtensions /// The instance this method extends. public static IApplicationBuilder UseResponseCompression(this IApplicationBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return builder.UseMiddleware(); } diff --git a/src/Middleware/ResponseCompression/src/ResponseCompressionMiddleware.cs b/src/Middleware/ResponseCompression/src/ResponseCompressionMiddleware.cs index 25f90ef6285b..22a9677d6e10 100644 --- a/src/Middleware/ResponseCompression/src/ResponseCompressionMiddleware.cs +++ b/src/Middleware/ResponseCompression/src/ResponseCompressionMiddleware.cs @@ -22,14 +22,8 @@ public class ResponseCompressionMiddleware /// The . public ResponseCompressionMiddleware(RequestDelegate next, IResponseCompressionProvider provider) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(provider); _next = next; _provider = provider; diff --git a/src/Middleware/ResponseCompression/src/ResponseCompressionProvider.cs b/src/Middleware/ResponseCompression/src/ResponseCompressionProvider.cs index fcf6058aacb0..4b31aacfca68 100644 --- a/src/Middleware/ResponseCompression/src/ResponseCompressionProvider.cs +++ b/src/Middleware/ResponseCompression/src/ResponseCompressionProvider.cs @@ -29,14 +29,8 @@ public class ResponseCompressionProvider : IResponseCompressionProvider /// The options for this instance. public ResponseCompressionProvider(IServiceProvider services, IOptions options) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(options); var responseCompressionOptions = options.Value; diff --git a/src/Middleware/ResponseCompression/src/ResponseCompressionServicesExtensions.cs b/src/Middleware/ResponseCompression/src/ResponseCompressionServicesExtensions.cs index b62c0bd7088d..624f7640bc16 100644 --- a/src/Middleware/ResponseCompression/src/ResponseCompressionServicesExtensions.cs +++ b/src/Middleware/ResponseCompression/src/ResponseCompressionServicesExtensions.cs @@ -19,10 +19,7 @@ public static class ResponseCompressionServicesExtensions /// The . public static IServiceCollection AddResponseCompression(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); return services; @@ -36,14 +33,8 @@ public static IServiceCollection AddResponseCompression(this IServiceCollection /// The . public static IServiceCollection AddResponseCompression(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.Configure(configureOptions); services.TryAddSingleton(); diff --git a/src/Middleware/Rewrite/src/ApacheModRewriteOptionsExtensions.cs b/src/Middleware/Rewrite/src/ApacheModRewriteOptionsExtensions.cs index 73948e0f27b6..e799cd8276b6 100644 --- a/src/Middleware/Rewrite/src/ApacheModRewriteOptionsExtensions.cs +++ b/src/Middleware/Rewrite/src/ApacheModRewriteOptionsExtensions.cs @@ -19,15 +19,8 @@ public static class ApacheModRewriteOptionsExtensions /// The path to the file containing mod_rewrite rules. public static RewriteOptions AddApacheModRewrite(this RewriteOptions options, IFileProvider fileProvider, string filePath) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileProvider); var fileInfo = fileProvider.GetFileInfo(filePath); using (var stream = fileInfo.CreateReadStream()) @@ -43,15 +36,8 @@ public static RewriteOptions AddApacheModRewrite(this RewriteOptions options, IF /// A stream of mod_rewrite rules. public static RewriteOptions AddApacheModRewrite(this RewriteOptions options, TextReader reader) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(reader); var rules = FileParser.Parse(reader); foreach (var rule in rules) diff --git a/src/Middleware/Rewrite/src/IISUrlRewrite/RewriteMapParser.cs b/src/Middleware/Rewrite/src/IISUrlRewrite/RewriteMapParser.cs index b3af8e7154b7..fce6afd7894d 100644 --- a/src/Middleware/Rewrite/src/IISUrlRewrite/RewriteMapParser.cs +++ b/src/Middleware/Rewrite/src/IISUrlRewrite/RewriteMapParser.cs @@ -10,10 +10,7 @@ internal static class RewriteMapParser { public static IISRewriteMapCollection? Parse(XElement xmlRoot) { - if (xmlRoot == null) - { - throw new ArgumentNullException(nameof(xmlRoot)); - } + ArgumentNullException.ThrowIfNull(xmlRoot); var mapsElement = xmlRoot.Descendants(RewriteTags.RewriteMaps).SingleOrDefault(); if (mapsElement == null) diff --git a/src/Middleware/Rewrite/src/IISUrlRewrite/UrlRewriteRuleBuilder.cs b/src/Middleware/Rewrite/src/IISUrlRewrite/UrlRewriteRuleBuilder.cs index ca7aa3a99d71..8d4942a85673 100644 --- a/src/Middleware/Rewrite/src/IISUrlRewrite/UrlRewriteRuleBuilder.cs +++ b/src/Middleware/Rewrite/src/IISUrlRewrite/UrlRewriteRuleBuilder.cs @@ -75,10 +75,7 @@ public void AddUrlCondition(Condition condition) { throw new InvalidOperationException($"You must first configure condition behavior by calling {nameof(ConfigureConditionBehavior)}"); } - if (condition == null) - { - throw new ArgumentNullException(nameof(condition)); - } + ArgumentNullException.ThrowIfNull(condition); _conditions.Add(condition); } diff --git a/src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs b/src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs index 75d2f5d0559f..49ab1e632097 100644 --- a/src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs +++ b/src/Middleware/Rewrite/src/IISUrlRewriteOptionsExtensions.cs @@ -23,15 +23,8 @@ public static class IISUrlRewriteOptionsExtensions [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Required for backwards compatability")] public static RewriteOptions AddIISUrlRewrite(this RewriteOptions options, IFileProvider fileProvider, string filePath, bool alwaysUseManagedServerVariables = false) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(fileProvider); var file = fileProvider.GetFileInfo(filePath); @@ -50,15 +43,8 @@ public static RewriteOptions AddIISUrlRewrite(this RewriteOptions options, IFile [SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "")] public static RewriteOptions AddIISUrlRewrite(this RewriteOptions options, TextReader reader, bool alwaysUseManagedServerVariables = false) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(reader); var rules = new UrlRewriteFileParser().Parse(reader, alwaysUseManagedServerVariables); diff --git a/src/Middleware/Rewrite/src/RedirectToNonWwwRule.cs b/src/Middleware/Rewrite/src/RedirectToNonWwwRule.cs index 471b94b2a16e..4768c694e2de 100644 --- a/src/Middleware/Rewrite/src/RedirectToNonWwwRule.cs +++ b/src/Middleware/Rewrite/src/RedirectToNonWwwRule.cs @@ -20,10 +20,7 @@ public RedirectToNonWwwRule(int statusCode) public RedirectToNonWwwRule(int statusCode, params string[] domains) { - if (domains == null) - { - throw new ArgumentNullException(nameof(domains)); - } + ArgumentNullException.ThrowIfNull(domains); if (domains.Length < 1) { diff --git a/src/Middleware/Rewrite/src/RedirectToWwwRule.cs b/src/Middleware/Rewrite/src/RedirectToWwwRule.cs index de333ec9a750..437f426c6d8c 100644 --- a/src/Middleware/Rewrite/src/RedirectToWwwRule.cs +++ b/src/Middleware/Rewrite/src/RedirectToWwwRule.cs @@ -20,10 +20,7 @@ public RedirectToWwwRule(int statusCode) public RedirectToWwwRule(int statusCode, params string[] domains) { - if (domains == null) - { - throw new ArgumentNullException(nameof(domains)); - } + ArgumentNullException.ThrowIfNull(domains); if (domains.Length < 1) { diff --git a/src/Middleware/Rewrite/src/RewriteBuilderExtensions.cs b/src/Middleware/Rewrite/src/RewriteBuilderExtensions.cs index f56d7ee850f8..7bbc49f9ed60 100644 --- a/src/Middleware/Rewrite/src/RewriteBuilderExtensions.cs +++ b/src/Middleware/Rewrite/src/RewriteBuilderExtensions.cs @@ -22,10 +22,7 @@ public static class RewriteBuilderExtensions /// public static IApplicationBuilder UseRewriter(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return AddRewriteMiddleware(app, options: null); } @@ -38,15 +35,8 @@ public static IApplicationBuilder UseRewriter(this IApplicationBuilder app) /// public static IApplicationBuilder UseRewriter(this IApplicationBuilder app, RewriteOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); // put middleware in pipeline return AddRewriteMiddleware(app, Options.Create(options)); diff --git a/src/Middleware/Rewrite/src/RewriteMiddleware.cs b/src/Middleware/Rewrite/src/RewriteMiddleware.cs index 42b73e50e8af..d76ea33d21f5 100644 --- a/src/Middleware/Rewrite/src/RewriteMiddleware.cs +++ b/src/Middleware/Rewrite/src/RewriteMiddleware.cs @@ -35,15 +35,8 @@ public RewriteMiddleware( ILoggerFactory loggerFactory, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; @@ -58,10 +51,7 @@ public RewriteMiddleware( /// A task that represents the execution of this middleware. public Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var rewriteContext = new RewriteContext { diff --git a/src/Middleware/Session/src/CookieProtection.cs b/src/Middleware/Session/src/CookieProtection.cs index ac62ba63084e..777b5df1a997 100644 --- a/src/Middleware/Session/src/CookieProtection.cs +++ b/src/Middleware/Session/src/CookieProtection.cs @@ -11,10 +11,7 @@ internal static class CookieProtection { internal static string Protect(IDataProtector protector, string data) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } + ArgumentNullException.ThrowIfNull(protector); if (string.IsNullOrEmpty(data)) { return data; diff --git a/src/Middleware/Session/src/DistributedSession.cs b/src/Middleware/Session/src/DistributedSession.cs index 5b538be20b60..6a3ce81be6de 100644 --- a/src/Middleware/Session/src/DistributedSession.cs +++ b/src/Middleware/Session/src/DistributedSession.cs @@ -60,25 +60,15 @@ public DistributedSession( ILoggerFactory loggerFactory, bool isNewSessionKey) { - if (cache == null) - { - throw new ArgumentNullException(nameof(cache)); - } + ArgumentNullException.ThrowIfNull(cache); if (string.IsNullOrEmpty(sessionKey)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(sessionKey)); } - if (tryEstablishSession == null) - { - throw new ArgumentNullException(nameof(tryEstablishSession)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(tryEstablishSession); + ArgumentNullException.ThrowIfNull(loggerFactory); _cache = cache; _sessionKey = sessionKey; @@ -150,10 +140,7 @@ public bool TryGetValue(string key, [NotNullWhen(true)] out byte[]? value) /// public void Set(string key, byte[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (IsAvailable) { diff --git a/src/Middleware/Session/src/DistributedSessionStore.cs b/src/Middleware/Session/src/DistributedSessionStore.cs index 3786ca452646..785206f2a78f 100644 --- a/src/Middleware/Session/src/DistributedSessionStore.cs +++ b/src/Middleware/Session/src/DistributedSessionStore.cs @@ -22,15 +22,8 @@ public class DistributedSessionStore : ISessionStore /// The . public DistributedSessionStore(IDistributedCache cache, ILoggerFactory loggerFactory) { - if (cache == null) - { - throw new ArgumentNullException(nameof(cache)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(cache); + ArgumentNullException.ThrowIfNull(loggerFactory); _cache = cache; _loggerFactory = loggerFactory; @@ -44,10 +37,7 @@ public ISession Create(string sessionKey, TimeSpan idleTimeout, TimeSpan ioTimeo throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(sessionKey)); } - if (tryEstablishSession == null) - { - throw new ArgumentNullException(nameof(tryEstablishSession)); - } + ArgumentNullException.ThrowIfNull(tryEstablishSession); return new DistributedSession(_cache, sessionKey, idleTimeout, ioTimeout, tryEstablishSession, _loggerFactory, isNewSessionKey); } diff --git a/src/Middleware/Session/src/SessionMiddleware.cs b/src/Middleware/Session/src/SessionMiddleware.cs index a81e36d11d8d..6d0882427801 100644 --- a/src/Middleware/Session/src/SessionMiddleware.cs +++ b/src/Middleware/Session/src/SessionMiddleware.cs @@ -39,30 +39,11 @@ public SessionMiddleware( ISessionStore sessionStore, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (dataProtectionProvider == null) - { - throw new ArgumentNullException(nameof(dataProtectionProvider)); - } - - if (sessionStore == null) - { - throw new ArgumentNullException(nameof(sessionStore)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(dataProtectionProvider); + ArgumentNullException.ThrowIfNull(sessionStore); + ArgumentNullException.ThrowIfNull(options); _next = next; _logger = loggerFactory.CreateLogger(); diff --git a/src/Middleware/Session/src/SessionMiddlewareExtensions.cs b/src/Middleware/Session/src/SessionMiddlewareExtensions.cs index b5723101db26..2d741940c94c 100644 --- a/src/Middleware/Session/src/SessionMiddlewareExtensions.cs +++ b/src/Middleware/Session/src/SessionMiddlewareExtensions.cs @@ -18,10 +18,7 @@ public static class SessionMiddlewareExtensions /// The . public static IApplicationBuilder UseSession(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -34,14 +31,8 @@ public static IApplicationBuilder UseSession(this IApplicationBuilder app) /// The . public static IApplicationBuilder UseSession(this IApplicationBuilder app, SessionOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/Session/src/SessionServiceCollectionExtensions.cs b/src/Middleware/Session/src/SessionServiceCollectionExtensions.cs index 40677414046f..314b1a624976 100644 --- a/src/Middleware/Session/src/SessionServiceCollectionExtensions.cs +++ b/src/Middleware/Session/src/SessionServiceCollectionExtensions.cs @@ -19,10 +19,7 @@ public static class SessionServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddSession(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddTransient(); services.AddDataProtection(); @@ -37,15 +34,8 @@ public static IServiceCollection AddSession(this IServiceCollection services) /// The so that additional calls can be chained. public static IServiceCollection AddSession(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configure); services.Configure(configure); services.AddSession(); diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddlewareExtensions.cs b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddlewareExtensions.cs index 8cc53fd77d71..ab3d0ced70e1 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddlewareExtensions.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddlewareExtensions.cs @@ -24,10 +24,7 @@ public static void UseAngularCliServer( this ISpaBuilder spaBuilder, string npmScript) { - if (spaBuilder == null) - { - throw new ArgumentNullException(nameof(spaBuilder)); - } + ArgumentNullException.ThrowIfNull(spaBuilder); var spaOptions = spaBuilder.Options; diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs index 4ed3c61cfe54..92a2bbcc5c2a 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/Proxying/SpaProxy.cs @@ -191,10 +191,7 @@ private static async Task CopyProxyHttpResponse(HttpContext context, HttpRespons private static Uri ToWebSocketScheme(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); var uriBuilder = new UriBuilder(uri); if (string.Equals(uriBuilder.Scheme, "https", StringComparison.OrdinalIgnoreCase)) @@ -211,15 +208,8 @@ private static Uri ToWebSocketScheme(Uri uri) private static async Task AcceptProxyWebSocketRequest(HttpContext context, Uri destinationUri, CancellationToken cancellationToken) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (destinationUri == null) - { - throw new ArgumentNullException(nameof(destinationUri)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(destinationUri); using (var client = new ClientWebSocket()) { @@ -281,10 +271,7 @@ await Task.WhenAll( private static async Task PumpWebSocket(WebSocket source, WebSocket destination, int bufferSize, CancellationToken cancellationToken) { - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); var buffer = new byte[bufferSize]; diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddlewareExtensions.cs b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddlewareExtensions.cs index 98449649087f..50424a9845bd 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddlewareExtensions.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddlewareExtensions.cs @@ -24,10 +24,7 @@ public static void UseReactDevelopmentServer( this ISpaBuilder spaBuilder, string npmScript) { - if (spaBuilder == null) - { - throw new ArgumentNullException(nameof(spaBuilder)); - } + ArgumentNullException.ThrowIfNull(spaBuilder); var spaOptions = spaBuilder.Options; diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/SpaApplicationBuilderExtensions.cs b/src/Middleware/Spa/SpaServices.Extensions/src/SpaApplicationBuilderExtensions.cs index 501d8007efb4..9f378bba58fa 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/SpaApplicationBuilderExtensions.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/SpaApplicationBuilderExtensions.cs @@ -27,10 +27,7 @@ public static class SpaApplicationBuilderExtensions /// public static void UseSpa(this IApplicationBuilder app, Action configuration) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(configuration); // Use the options configured in DI (or blank if none was configured). We have to clone it // otherwise if you have multiple UseSpa calls, their configurations would interfere with one another. diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs index 4e1af89de13e..bc240cd471d1 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/SpaDefaultPageMiddleware.cs @@ -13,10 +13,7 @@ internal sealed class SpaDefaultPageMiddleware { public static void Attach(ISpaBuilder spaBuilder) { - if (spaBuilder == null) - { - throw new ArgumentNullException(nameof(spaBuilder)); - } + ArgumentNullException.ThrowIfNull(spaBuilder); var app = spaBuilder.ApplicationBuilder; var options = spaBuilder.Options; diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs index 3350632e8c7e..4eb187885311 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs @@ -19,10 +19,7 @@ public DefaultSpaStaticFileProvider( IServiceProvider serviceProvider, SpaStaticFilesOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrEmpty(options.RootPath)) { diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/SpaStaticFilesExtensions.cs b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/SpaStaticFilesExtensions.cs index acec9b283417..aa3532eddab0 100644 --- a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/SpaStaticFilesExtensions.cs +++ b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/SpaStaticFilesExtensions.cs @@ -61,15 +61,8 @@ public static void UseSpaStaticFiles(this IApplicationBuilder applicationBuilder /// Specifies options for serving the static files. public static void UseSpaStaticFiles(this IApplicationBuilder applicationBuilder, StaticFileOptions options) { - if (applicationBuilder == null) - { - throw new ArgumentNullException(nameof(applicationBuilder)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(applicationBuilder); + ArgumentNullException.ThrowIfNull(options); UseSpaStaticFilesInternal(applicationBuilder, staticFileOptions: options, @@ -81,10 +74,7 @@ internal static void UseSpaStaticFilesInternal( StaticFileOptions staticFileOptions, bool allowFallbackOnServingWebRootFiles) { - if (staticFileOptions == null) - { - throw new ArgumentNullException(nameof(staticFileOptions)); - } + ArgumentNullException.ThrowIfNull(staticFileOptions); // If the file provider was explicitly supplied, that takes precedence over any other // configured file provider. This is most useful if the application hosts multiple SPAs diff --git a/src/Middleware/StaticFiles/src/DefaultFilesExtensions.cs b/src/Middleware/StaticFiles/src/DefaultFilesExtensions.cs index 21b51e265738..05340b6750d2 100644 --- a/src/Middleware/StaticFiles/src/DefaultFilesExtensions.cs +++ b/src/Middleware/StaticFiles/src/DefaultFilesExtensions.cs @@ -24,10 +24,7 @@ public static class DefaultFilesExtensions /// public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -44,10 +41,7 @@ public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app) /// public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app, string requestPath) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseDefaultFiles(new DefaultFilesOptions { @@ -63,14 +57,8 @@ public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app, /// public static IApplicationBuilder UseDefaultFiles(this IApplicationBuilder app, DefaultFilesOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/StaticFiles/src/DefaultFilesMiddleware.cs b/src/Middleware/StaticFiles/src/DefaultFilesMiddleware.cs index 318aacd52e27..ca010ec0282f 100644 --- a/src/Middleware/StaticFiles/src/DefaultFilesMiddleware.cs +++ b/src/Middleware/StaticFiles/src/DefaultFilesMiddleware.cs @@ -29,20 +29,9 @@ public class DefaultFilesMiddleware /// The configuration options for this middleware. public DefaultFilesMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (hostingEnv == null) - { - throw new ArgumentNullException(nameof(hostingEnv)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(hostingEnv); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; diff --git a/src/Middleware/StaticFiles/src/DirectoryBrowserExtensions.cs b/src/Middleware/StaticFiles/src/DirectoryBrowserExtensions.cs index 1c91f0d08f2d..bbbb70dd3c9c 100644 --- a/src/Middleware/StaticFiles/src/DirectoryBrowserExtensions.cs +++ b/src/Middleware/StaticFiles/src/DirectoryBrowserExtensions.cs @@ -24,10 +24,7 @@ public static class DirectoryBrowserExtensions /// public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -44,10 +41,7 @@ public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder a /// public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app, string requestPath) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseDirectoryBrowser(new DirectoryBrowserOptions { @@ -63,14 +57,8 @@ public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder a /// public static IApplicationBuilder UseDirectoryBrowser(this IApplicationBuilder app, DirectoryBrowserOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/StaticFiles/src/DirectoryBrowserMiddleware.cs b/src/Middleware/StaticFiles/src/DirectoryBrowserMiddleware.cs index c0929c013b7e..87458d008dc6 100644 --- a/src/Middleware/StaticFiles/src/DirectoryBrowserMiddleware.cs +++ b/src/Middleware/StaticFiles/src/DirectoryBrowserMiddleware.cs @@ -41,25 +41,10 @@ public DirectoryBrowserMiddleware(RequestDelegate next, IWebHostEnvironment host /// The configuration for this middleware. public DirectoryBrowserMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, HtmlEncoder encoder, IOptions options) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (hostingEnv == null) - { - throw new ArgumentNullException(nameof(hostingEnv)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(hostingEnv); + ArgumentNullException.ThrowIfNull(encoder); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; diff --git a/src/Middleware/StaticFiles/src/DirectoryBrowserServiceExtensions.cs b/src/Middleware/StaticFiles/src/DirectoryBrowserServiceExtensions.cs index dc4473892abf..5a392cc03827 100644 --- a/src/Middleware/StaticFiles/src/DirectoryBrowserServiceExtensions.cs +++ b/src/Middleware/StaticFiles/src/DirectoryBrowserServiceExtensions.cs @@ -15,10 +15,7 @@ public static class DirectoryBrowserServiceExtensions /// The so that additional calls can be chained. public static IServiceCollection AddDirectoryBrowser(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddWebEncoders(); diff --git a/src/Middleware/StaticFiles/src/FileExtensionContentTypeProvider.cs b/src/Middleware/StaticFiles/src/FileExtensionContentTypeProvider.cs index 6af230121250..541b43e3d1ae 100644 --- a/src/Middleware/StaticFiles/src/FileExtensionContentTypeProvider.cs +++ b/src/Middleware/StaticFiles/src/FileExtensionContentTypeProvider.cs @@ -414,10 +414,7 @@ public FileExtensionContentTypeProvider() /// public FileExtensionContentTypeProvider(IDictionary mapping) { - if (mapping == null) - { - throw new ArgumentNullException(nameof(mapping)); - } + ArgumentNullException.ThrowIfNull(mapping); Mappings = mapping; } diff --git a/src/Middleware/StaticFiles/src/FileServerExtensions.cs b/src/Middleware/StaticFiles/src/FileServerExtensions.cs index 42dc3c1a6cab..05d3dde82405 100644 --- a/src/Middleware/StaticFiles/src/FileServerExtensions.cs +++ b/src/Middleware/StaticFiles/src/FileServerExtensions.cs @@ -23,10 +23,7 @@ public static class FileServerExtensions /// public static IApplicationBuilder UseFileServer(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseFileServer(new FileServerOptions()); } @@ -43,10 +40,7 @@ public static IApplicationBuilder UseFileServer(this IApplicationBuilder app) /// public static IApplicationBuilder UseFileServer(this IApplicationBuilder app, bool enableDirectoryBrowsing) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseFileServer(new FileServerOptions { @@ -66,15 +60,8 @@ public static IApplicationBuilder UseFileServer(this IApplicationBuilder app, bo /// public static IApplicationBuilder UseFileServer(this IApplicationBuilder app, string requestPath) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (requestPath == null) - { - throw new ArgumentNullException(nameof(requestPath)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(requestPath); return app.UseFileServer(new FileServerOptions { @@ -90,14 +77,8 @@ public static IApplicationBuilder UseFileServer(this IApplicationBuilder app, st /// public static IApplicationBuilder UseFileServer(this IApplicationBuilder app, FileServerOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); if (options.EnableDefaultFiles) { diff --git a/src/Middleware/StaticFiles/src/HtmlDirectoryFormatter.cs b/src/Middleware/StaticFiles/src/HtmlDirectoryFormatter.cs index 91f02be11bfd..449133a15be0 100644 --- a/src/Middleware/StaticFiles/src/HtmlDirectoryFormatter.cs +++ b/src/Middleware/StaticFiles/src/HtmlDirectoryFormatter.cs @@ -25,10 +25,7 @@ public class HtmlDirectoryFormatter : IDirectoryFormatter /// The character encoding representation to use. public HtmlDirectoryFormatter(HtmlEncoder encoder) { - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(encoder); _htmlEncoder = encoder; } @@ -37,14 +34,8 @@ public HtmlDirectoryFormatter(HtmlEncoder encoder) /// public virtual Task GenerateContentAsync(HttpContext context, IEnumerable contents) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (contents == null) - { - throw new ArgumentNullException(nameof(contents)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(contents); context.Response.ContentType = TextHtmlUtf8; diff --git a/src/Middleware/StaticFiles/src/Infrastructure/SharedOptionsBase.cs b/src/Middleware/StaticFiles/src/Infrastructure/SharedOptionsBase.cs index bc01b8646707..ad9c2fce0ca8 100644 --- a/src/Middleware/StaticFiles/src/Infrastructure/SharedOptionsBase.cs +++ b/src/Middleware/StaticFiles/src/Infrastructure/SharedOptionsBase.cs @@ -18,10 +18,7 @@ public abstract class SharedOptionsBase /// protected SharedOptionsBase(SharedOptions sharedOptions) { - if (sharedOptions == null) - { - throw new ArgumentNullException(nameof(sharedOptions)); - } + ArgumentNullException.ThrowIfNull(sharedOptions); SharedOptions = sharedOptions; } diff --git a/src/Middleware/StaticFiles/src/StaticFileExtensions.cs b/src/Middleware/StaticFiles/src/StaticFileExtensions.cs index 5fec481dfc1d..3351d3da7b76 100644 --- a/src/Middleware/StaticFiles/src/StaticFileExtensions.cs +++ b/src/Middleware/StaticFiles/src/StaticFileExtensions.cs @@ -24,10 +24,7 @@ public static class StaticFileExtensions /// public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -44,10 +41,7 @@ public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app) /// public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, string requestPath) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseStaticFiles(new StaticFileOptions { @@ -63,14 +57,8 @@ public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, s /// public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs b/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs index 446024ffe732..7321d0cf43a6 100644 --- a/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs +++ b/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs @@ -31,25 +31,10 @@ public class StaticFileMiddleware /// An instance used to create loggers. public StaticFileMiddleware(RequestDelegate next, IWebHostEnvironment hostingEnv, IOptions options, ILoggerFactory loggerFactory) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - - if (hostingEnv == null) - { - throw new ArgumentNullException(nameof(hostingEnv)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(hostingEnv); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _next = next; _options = options.Value; diff --git a/src/Middleware/WebSockets/src/WebSocketMiddleware.cs b/src/Middleware/WebSockets/src/WebSocketMiddleware.cs index 8f2bcca80ef6..c331de7ae895 100644 --- a/src/Middleware/WebSockets/src/WebSocketMiddleware.cs +++ b/src/Middleware/WebSockets/src/WebSocketMiddleware.cs @@ -33,14 +33,8 @@ public partial class WebSocketMiddleware /// An instance used to create loggers. public WebSocketMiddleware(RequestDelegate next, IOptions options, ILoggerFactory loggerFactory) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(options); _next = next; _options = options.Value; diff --git a/src/Middleware/WebSockets/src/WebSocketMiddlewareExtensions.cs b/src/Middleware/WebSockets/src/WebSocketMiddlewareExtensions.cs index 66ee9db2544c..fe5fb75bd5cb 100644 --- a/src/Middleware/WebSockets/src/WebSocketMiddlewareExtensions.cs +++ b/src/Middleware/WebSockets/src/WebSocketMiddlewareExtensions.cs @@ -22,10 +22,7 @@ public static class WebSocketMiddlewareExtensions /// public static IApplicationBuilder UseWebSockets(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -44,14 +41,8 @@ public static IApplicationBuilder UseWebSockets(this IApplicationBuilder app) /// public static IApplicationBuilder UseWebSockets(this IApplicationBuilder app, WebSocketOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Middleware/WebSockets/src/WebSocketsDependencyInjectionExtensions.cs b/src/Middleware/WebSockets/src/WebSocketsDependencyInjectionExtensions.cs index a174262e74c4..8e240de639c0 100644 --- a/src/Middleware/WebSockets/src/WebSocketsDependencyInjectionExtensions.cs +++ b/src/Middleware/WebSockets/src/WebSocketsDependencyInjectionExtensions.cs @@ -19,10 +19,7 @@ public static class WebSocketsDependencyInjectionExtensions /// public static IServiceCollection AddWebSockets(this IServiceCollection services, Action configure) { - if (configure is null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); return services.Configure(configure); } diff --git a/src/Middleware/tools/RazorPageGenerator/Program.cs b/src/Middleware/tools/RazorPageGenerator/Program.cs index 0fcfa9993d54..1b0766bca094 100644 --- a/src/Middleware/tools/RazorPageGenerator/Program.cs +++ b/src/Middleware/tools/RazorPageGenerator/Program.cs @@ -145,10 +145,7 @@ private sealed class SuppressChecksumOptionsFeature : RazorEngineFeatureBase, IC public void Configure(RazorCodeGenerationOptionsBuilder options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.SuppressChecksum = true; } @@ -160,10 +157,7 @@ private sealed class SuppressMetadataAttributesFeature : RazorEngineFeatureBase, public void Configure(RazorCodeGenerationOptionsBuilder options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.SuppressMetadataAttributes = true; } diff --git a/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionDescriptorExtensions.cs b/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionDescriptorExtensions.cs index 419d6beeaca8..6611e9944788 100644 --- a/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionDescriptorExtensions.cs +++ b/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionDescriptorExtensions.cs @@ -17,10 +17,7 @@ public static class ActionDescriptorExtensions /// The property or the default value of . public static T? GetProperty(this ActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (actionDescriptor.Properties.TryGetValue(typeof(T), out var value)) { @@ -41,10 +38,7 @@ public static class ActionDescriptorExtensions /// The value of the property. public static void SetProperty(this ActionDescriptor actionDescriptor, T value) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (value == null) { diff --git a/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionInvokerProviderContext.cs b/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionInvokerProviderContext.cs index e9e8c1cabbc7..113ba835a294 100644 --- a/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionInvokerProviderContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Abstractions/ActionInvokerProviderContext.cs @@ -14,10 +14,7 @@ public class ActionInvokerProviderContext /// The to invoke. public ActionInvokerProviderContext(ActionContext actionContext) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } + ArgumentNullException.ThrowIfNull(actionContext); ActionContext = actionContext; } diff --git a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintItem.cs b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintItem.cs index 34fa9412b89d..86ef60038695 100644 --- a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintItem.cs +++ b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintItem.cs @@ -15,10 +15,7 @@ public class ActionConstraintItem /// The instance. public ActionConstraintItem(IActionConstraintMetadata metadata) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadata); Metadata = metadata; } diff --git a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintProviderContext.cs b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintProviderContext.cs index 7be50c1d23cc..ecafa3ff7944 100644 --- a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintProviderContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionConstraintProviderContext.cs @@ -22,20 +22,9 @@ public ActionConstraintProviderContext( ActionDescriptor action, IList items) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(items); HttpContext = context; Action = action; diff --git a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionSelectorCandidate.cs b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionSelectorCandidate.cs index 91f4492a1930..7812e8e74d61 100644 --- a/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionSelectorCandidate.cs +++ b/src/Mvc/Mvc.Abstractions/src/ActionConstraints/ActionSelectorCandidate.cs @@ -19,10 +19,7 @@ public readonly struct ActionSelectorCandidate /// public ActionSelectorCandidate(ActionDescriptor action, IReadOnlyList? constraints) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); Action = action; Constraints = constraints; diff --git a/src/Mvc/Mvc.Abstractions/src/ActionContext.cs b/src/Mvc/Mvc.Abstractions/src/ActionContext.cs index b93301bf8202..de71cbd0c18a 100644 --- a/src/Mvc/Mvc.Abstractions/src/ActionContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/ActionContext.cs @@ -64,25 +64,10 @@ public ActionContext( ActionDescriptor actionDescriptor, ModelStateDictionary modelState) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (routeData == null) - { - throw new ArgumentNullException(nameof(routeData)); - } - - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(routeData); + ArgumentNullException.ThrowIfNull(actionDescriptor); + ArgumentNullException.ThrowIfNull(modelState); HttpContext = httpContext; RouteData = routeData; diff --git a/src/Mvc/Mvc.Abstractions/src/ApiExplorer/ApiDescriptionProviderContext.cs b/src/Mvc/Mvc.Abstractions/src/ApiExplorer/ApiDescriptionProviderContext.cs index 46467b5c0515..fb40b605d5b8 100644 --- a/src/Mvc/Mvc.Abstractions/src/ApiExplorer/ApiDescriptionProviderContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/ApiExplorer/ApiDescriptionProviderContext.cs @@ -16,10 +16,7 @@ public class ApiDescriptionProviderContext /// The list of actions. public ApiDescriptionProviderContext(IReadOnlyList actions) { - if (actions == null) - { - throw new ArgumentNullException(nameof(actions)); - } + ArgumentNullException.ThrowIfNull(actions); Actions = actions; diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/ActionExecutingContext.cs b/src/Mvc/Mvc.Abstractions/src/Filters/ActionExecutingContext.cs index f8f6723fc5fe..6f8f8211b385 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/ActionExecutingContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/ActionExecutingContext.cs @@ -27,10 +27,7 @@ public ActionExecutingContext( object controller) : base(actionContext, filters) { - if (actionArguments == null) - { - throw new ArgumentNullException(nameof(actionArguments)); - } + ArgumentNullException.ThrowIfNull(actionArguments); ActionArguments = actionArguments; Controller = controller; diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/FilterContext.cs b/src/Mvc/Mvc.Abstractions/src/Filters/FilterContext.cs index ad228403001b..46bf91d08180 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/FilterContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/FilterContext.cs @@ -20,10 +20,7 @@ public FilterContext( IList filters) : base(actionContext) { - if (filters == null) - { - throw new ArgumentNullException(nameof(filters)); - } + ArgumentNullException.ThrowIfNull(filters); Filters = filters; } diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/FilterDescriptor.cs b/src/Mvc/Mvc.Abstractions/src/Filters/FilterDescriptor.cs index e9259fe9389c..1ea7c7dd1f37 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/FilterDescriptor.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/FilterDescriptor.cs @@ -36,10 +36,7 @@ public class FilterDescriptor /// public FilterDescriptor(IFilterMetadata filter, int filterScope) { - if (filter == null) - { - throw new ArgumentNullException(nameof(filter)); - } + ArgumentNullException.ThrowIfNull(filter); Filter = filter; Scope = filterScope; diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/FilterItem.cs b/src/Mvc/Mvc.Abstractions/src/Filters/FilterItem.cs index 9846d0dc930f..c7733a1c2405 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/FilterItem.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/FilterItem.cs @@ -20,10 +20,7 @@ public class FilterItem /// The . public FilterItem(FilterDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); Descriptor = descriptor; } @@ -36,10 +33,7 @@ public FilterItem(FilterDescriptor descriptor) public FilterItem(FilterDescriptor descriptor, IFilterMetadata filter) : this(descriptor) { - if (filter == null) - { - throw new ArgumentNullException(nameof(filter)); - } + ArgumentNullException.ThrowIfNull(filter); Filter = filter; } diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/FilterProviderContext.cs b/src/Mvc/Mvc.Abstractions/src/Filters/FilterProviderContext.cs index d7cadd1db8c7..dca6f83ed336 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/FilterProviderContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/FilterProviderContext.cs @@ -17,15 +17,8 @@ public class FilterProviderContext /// public FilterProviderContext(ActionContext actionContext, IList items) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(items); ActionContext = actionContext; Results = items; diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/ResourceExecutingContext.cs b/src/Mvc/Mvc.Abstractions/src/Filters/ResourceExecutingContext.cs index 7e095ffe001c..51b54899d248 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/ResourceExecutingContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/ResourceExecutingContext.cs @@ -23,10 +23,7 @@ public ResourceExecutingContext( IList valueProviderFactories) : base(actionContext, filters) { - if (valueProviderFactories == null) - { - throw new ArgumentNullException(nameof(valueProviderFactories)); - } + ArgumentNullException.ThrowIfNull(valueProviderFactories); ValueProviderFactories = valueProviderFactories; } diff --git a/src/Mvc/Mvc.Abstractions/src/Filters/ResultExecutedContext.cs b/src/Mvc/Mvc.Abstractions/src/Filters/ResultExecutedContext.cs index 766da2bbb7d7..7482e47f8e03 100644 --- a/src/Mvc/Mvc.Abstractions/src/Filters/ResultExecutedContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Filters/ResultExecutedContext.cs @@ -29,10 +29,7 @@ public ResultExecutedContext( object controller) : base(actionContext, filters) { - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(result); Result = result; Controller = controller; diff --git a/src/Mvc/Mvc.Abstractions/src/Formatters/InputFormatterContext.cs b/src/Mvc/Mvc.Abstractions/src/Formatters/InputFormatterContext.cs index 481ff76c41d3..722c14960de8 100644 --- a/src/Mvc/Mvc.Abstractions/src/Formatters/InputFormatterContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Formatters/InputFormatterContext.cs @@ -65,30 +65,11 @@ public InputFormatterContext( Func readerFactory, bool treatEmptyInputAsDefaultValue) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (modelName == null) - { - throw new ArgumentNullException(nameof(modelName)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - - if (readerFactory == null) - { - throw new ArgumentNullException(nameof(readerFactory)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(modelName); + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(readerFactory); HttpContext = httpContext; ModelName = modelName; diff --git a/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterCanWriteContext.cs b/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterCanWriteContext.cs index d87faa04f693..92a2b1e9bd1d 100644 --- a/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterCanWriteContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterCanWriteContext.cs @@ -17,10 +17,7 @@ public abstract class OutputFormatterCanWriteContext /// The for the current request. protected OutputFormatterCanWriteContext(HttpContext httpContext) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); HttpContext = httpContext; } diff --git a/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterWriteContext.cs b/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterWriteContext.cs index 6e23ef74e8c5..795c1933de91 100644 --- a/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterWriteContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/Formatters/OutputFormatterWriteContext.cs @@ -21,10 +21,7 @@ public class OutputFormatterWriteContext : OutputFormatterCanWriteContext public OutputFormatterWriteContext(HttpContext httpContext, Func writerFactory, Type? objectType, object? @object) : base(httpContext) { - if (writerFactory == null) - { - throw new ArgumentNullException(nameof(writerFactory)); - } + ArgumentNullException.ThrowIfNull(writerFactory); WriterFactory = writerFactory; ObjectType = objectType; diff --git a/src/Mvc/Mvc.Abstractions/src/Microsoft.AspNetCore.Mvc.Abstractions.csproj b/src/Mvc/Mvc.Abstractions/src/Microsoft.AspNetCore.Mvc.Abstractions.csproj index 6306e86b9049..aff03e70c69e 100644 --- a/src/Mvc/Mvc.Abstractions/src/Microsoft.AspNetCore.Mvc.Abstractions.csproj +++ b/src/Mvc/Mvc.Abstractions/src/Microsoft.AspNetCore.Mvc.Abstractions.csproj @@ -15,6 +15,8 @@ Microsoft.AspNetCore.Mvc.IActionResult + + diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingInfo.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingInfo.cs index a112b90bd78e..ad294bf6a52d 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingInfo.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingInfo.cs @@ -27,10 +27,7 @@ public BindingInfo() /// The to copy. public BindingInfo(BindingInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); BindingSource = other.BindingSource; BinderModelName = other.BinderModelName; @@ -183,15 +180,8 @@ public Type? BinderType /// A new instance of if any binding metadata was discovered; otherwise or . public static BindingInfo? GetBindingInfo(IEnumerable attributes, ModelMetadata modelMetadata) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } - - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } + ArgumentNullException.ThrowIfNull(attributes); + ArgumentNullException.ThrowIfNull(modelMetadata); var bindingInfo = GetBindingInfo(attributes); var isBindingInfoPresent = bindingInfo != null; @@ -217,10 +207,7 @@ public Type? BinderType /// otherwise. public bool TryApplyBindingInfo(ModelMetadata modelMetadata) { - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } + ArgumentNullException.ThrowIfNull(modelMetadata); var isBindingInfoPresent = false; if (BinderModelName == null && modelMetadata.BinderModelName != null) diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingSource.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingSource.cs index 8c3036319a10..3d094203a89b 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingSource.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/BindingSource.cs @@ -115,10 +115,7 @@ public class BindingSource : IEquatable /// public BindingSource(string id, string displayName, bool isGreedy, bool isFromRequest) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } + ArgumentNullException.ThrowIfNull(id); Id = id; DisplayName = displayName; @@ -182,10 +179,7 @@ public BindingSource(string id, string displayName, bool isGreedy, bool isFromRe /// public virtual bool CanAcceptDataFrom(BindingSource bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } + ArgumentNullException.ThrowIfNull(bindingSource); if (bindingSource is CompositeBindingSource) { diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/CompositeBindingSource.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/CompositeBindingSource.cs index b2e226278d7b..63da0fd9cf9a 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/CompositeBindingSource.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/CompositeBindingSource.cs @@ -24,10 +24,7 @@ public static CompositeBindingSource Create( IEnumerable bindingSources, string displayName) { - if (bindingSources == null) - { - throw new ArgumentNullException(nameof(bindingSources)); - } + ArgumentNullException.ThrowIfNull(bindingSources); foreach (var bindingSource in bindingSources) { @@ -66,15 +63,8 @@ private CompositeBindingSource( IEnumerable bindingSources) : base(id, displayName, isGreedy: false, isFromRequest: true) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - - if (bindingSources == null) - { - throw new ArgumentNullException(nameof(bindingSources)); - } + ArgumentNullException.ThrowIfNull(id); + ArgumentNullException.ThrowIfNull(bindingSources); BindingSources = bindingSources; } @@ -87,10 +77,7 @@ private CompositeBindingSource( /// public override bool CanAcceptDataFrom(BindingSource bindingSource) { - if (bindingSource is null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } + ArgumentNullException.ThrowIfNull(bindingSource); if (bindingSource is CompositeBindingSource) { diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/EnumGroupAndName.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/EnumGroupAndName.cs index b6c3375906b9..8ca4e525be56 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/EnumGroupAndName.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/EnumGroupAndName.cs @@ -18,15 +18,8 @@ public readonly struct EnumGroupAndName /// The name. public EnumGroupAndName(string group, string name) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(name); Group = group; _name = () => name; @@ -41,15 +34,8 @@ public EnumGroupAndName( string group, Func name) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(name); Group = group; _name = name; diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Metadata/ModelMetadataIdentity.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Metadata/ModelMetadataIdentity.cs index eef3e15155f6..e56fa69d2045 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Metadata/ModelMetadataIdentity.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Metadata/ModelMetadataIdentity.cs @@ -32,10 +32,7 @@ private ModelMetadataIdentity( /// A . public static ModelMetadataIdentity ForType(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); return new ModelMetadataIdentity(modelType); } @@ -53,15 +50,8 @@ public static ModelMetadataIdentity ForProperty( string name, Type containerType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (containerType == null) - { - throw new ArgumentNullException(nameof(containerType)); - } + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(containerType); if (string.IsNullOrEmpty(name)) { @@ -83,20 +73,9 @@ public static ModelMetadataIdentity ForProperty( Type modelType, Type containerType) { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (containerType == null) - { - throw new ArgumentNullException(nameof(containerType)); - } + ArgumentNullException.ThrowIfNull(propertyInfo); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(containerType); return new ModelMetadataIdentity(modelType, propertyInfo.Name, containerType, fieldInfo: propertyInfo); } @@ -118,15 +97,8 @@ public static ModelMetadataIdentity ForParameter(ParameterInfo parameter) /// A . public static ModelMetadataIdentity ForParameter(ParameterInfo parameter, Type modelType) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(parameter); + ArgumentNullException.ThrowIfNull(modelType); return new ModelMetadataIdentity(modelType, parameter.Name, fieldInfo: parameter); } @@ -140,15 +112,8 @@ public static ModelMetadataIdentity ForParameter(ParameterInfo parameter, Type m /// A . public static ModelMetadataIdentity ForConstructor(ConstructorInfo constructor, Type modelType) { - if (constructor == null) - { - throw new ArgumentNullException(nameof(constructor)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(constructor); + ArgumentNullException.ThrowIfNull(modelType); return new ModelMetadataIdentity(modelType, constructor.Name, constructorInfo: constructor); } diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelErrorCollection.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelErrorCollection.cs index 8b7c99336801..97bbb3ce1594 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelErrorCollection.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelErrorCollection.cs @@ -16,10 +16,7 @@ public class ModelErrorCollection : Collection /// The public void Add(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); Add(new ModelError(exception)); } @@ -30,10 +27,7 @@ public void Add(Exception exception) /// The error message. public void Add(string errorMessage) { - if (errorMessage == null) - { - throw new ArgumentNullException(nameof(errorMessage)); - } + ArgumentNullException.ThrowIfNull(errorMessage); Add(new ModelError(errorMessage)); } diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelPropertyCollection.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelPropertyCollection.cs index 3b8f03abb0d8..95a33488c8ed 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelPropertyCollection.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelPropertyCollection.cs @@ -34,10 +34,7 @@ public ModelMetadata? this[string propertyName] { get { - if (propertyName == null) - { - throw new ArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(propertyName); for (var i = 0; i < Items.Count; i++) { diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelStateDictionary.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelStateDictionary.cs index a7082e2d5c6c..68ee772f6f4f 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelStateDictionary.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelStateDictionary.cs @@ -73,10 +73,7 @@ public ModelStateDictionary(ModelStateDictionary dictionary) dictionary?.MaxValidationDepth ?? DefaultMaxRecursionDepth, dictionary?.MaxStateDepth ?? DefaultMaxRecursionDepth) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } + ArgumentNullException.ThrowIfNull(dictionary); Merge(dictionary); } @@ -110,10 +107,7 @@ public int MaxAllowedErrors } set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _maxAllowedErrors = value; } @@ -174,10 +168,7 @@ public ModelStateEntry? this[string key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); TryGetValue(key, out var entry); return entry; @@ -211,15 +202,8 @@ public ModelStateEntry? this[string key] /// public bool TryAddModelException(string key, Exception exception) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(exception); if ((exception is InputFormatterException || exception is ValueProviderException) && !string.IsNullOrEmpty(exception.Message)) @@ -250,20 +234,9 @@ public bool TryAddModelException(string key, Exception exception) /// The associated with the model. public void AddModelError(string key, Exception exception, ModelMetadata metadata) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(exception); + ArgumentNullException.ThrowIfNull(metadata); TryAddModelError(key, exception, metadata); } @@ -284,20 +257,9 @@ public void AddModelError(string key, Exception exception, ModelMetadata metadat /// public bool TryAddModelError(string key, Exception exception, ModelMetadata metadata) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(exception); + ArgumentNullException.ThrowIfNull(metadata); if (ErrorCount >= MaxAllowedErrors - 1) { @@ -357,15 +319,8 @@ public bool TryAddModelError(string key, Exception exception, ModelMetadata meta /// The error message to add. public void AddModelError(string key, string errorMessage) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (errorMessage == null) - { - throw new ArgumentNullException(nameof(errorMessage)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(errorMessage); TryAddModelError(key, errorMessage); } @@ -384,15 +339,8 @@ public void AddModelError(string key, string errorMessage) /// public bool TryAddModelError(string key, string errorMessage) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (errorMessage == null) - { - throw new ArgumentNullException(nameof(errorMessage)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(errorMessage); if (ErrorCount >= MaxAllowedErrors - 1) { @@ -420,10 +368,7 @@ public bool TryAddModelError(string key, string errorMessage) /// state errors; otherwise. public ModelValidationState GetFieldValidationState(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var item = GetNode(key); return GetValidity(item, currentDepth: 0) ?? ModelValidationState.Unvalidated; @@ -438,10 +383,7 @@ public ModelValidationState GetFieldValidationState(string key) /// state errors; otherwise. public ModelValidationState GetValidationState(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (TryGetValue(key, out var validationState)) { @@ -458,10 +400,7 @@ public ModelValidationState GetValidationState(string key) /// The key of the to mark as valid. public void MarkFieldValid(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var modelState = GetOrAddNode(key); if (modelState.ValidationState == ModelValidationState.Invalid) @@ -481,10 +420,7 @@ public void MarkFieldValid(string key) /// The key of the to mark as skipped. public void MarkFieldSkipped(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var modelState = GetOrAddNode(key); if (modelState.ValidationState == ModelValidationState.Invalid) @@ -530,10 +466,7 @@ public void Merge(ModelStateDictionary dictionary) /// public void SetModelValue(string key, object? rawValue, string? attemptedValue) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var modelState = GetOrAddNode(key); Count += !modelState.IsContainerNode ? 0 : 1; @@ -551,10 +484,7 @@ public void SetModelValue(string key, object? rawValue, string? attemptedValue) /// public void SetModelValue(string key, ValueProviderResult valueProviderResult) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); // Avoid creating a new array for rawValue if there's only one value. object? rawValue; @@ -766,10 +696,7 @@ public void Clear() /// public bool ContainsKey(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return !GetNode(key)?.IsContainerNode ?? false; } @@ -782,10 +709,7 @@ public bool ContainsKey(string key) /// returns false if key was not found. public bool Remove(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var node = GetNode(key); if (node?.IsContainerNode == false) @@ -802,10 +726,7 @@ public bool Remove(string key) /// public bool TryGetValue(string key, [NotNullWhen(true)] out ModelStateEntry? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var result = GetNode(key); if (result?.IsContainerNode == false) @@ -839,15 +760,8 @@ public bool TryGetValue(string key, [NotNullWhen(true)] out ModelStateEntry? val /// public static bool StartsWithPrefix(string prefix, string key) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(key); if (prefix.Length == 0) { @@ -888,10 +802,7 @@ public static bool StartsWithPrefix(string prefix, string key) /// The . public PrefixEnumerable FindKeysWithPrefix(string prefix) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(prefix); return new PrefixEnumerable(this, prefix); } @@ -1066,15 +977,8 @@ private int BinarySearch(StringSegment searchKey) /// The prefix. public PrefixEnumerable(ModelStateDictionary dictionary, string prefix) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(prefix); _dictionary = dictionary; _prefix = prefix; @@ -1107,15 +1011,8 @@ public struct Enumerator : IEnumerator> /// The prefix. public Enumerator(ModelStateDictionary dictionary, string prefix) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(prefix); _index = -1; _rootNode = dictionary.GetNode(prefix); diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/TooManyModelErrorsException.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/TooManyModelErrorsException.cs index e7c231a11daf..320389fae77f 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/TooManyModelErrorsException.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/TooManyModelErrorsException.cs @@ -16,9 +16,6 @@ public class TooManyModelErrorsException : Exception public TooManyModelErrorsException(string message) : base(message) { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(message); } } diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ModelValidationContextBase.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ModelValidationContextBase.cs index 3c81bd2b48cd..06a54ccc4f80 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ModelValidationContextBase.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ModelValidationContextBase.cs @@ -19,20 +19,9 @@ public ModelValidationContextBase( ModelMetadata modelMetadata, IModelMetadataProvider metadataProvider) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(modelMetadata); + ArgumentNullException.ThrowIfNull(metadataProvider); ActionContext = actionContext; ModelMetadata = modelMetadata; diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ValidationEntry.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ValidationEntry.cs index 2c77189ef4e5..dabd33e5a241 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ValidationEntry.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/Validation/ValidationEntry.cs @@ -19,15 +19,8 @@ public struct ValidationEntry /// The model object. public ValidationEntry(ModelMetadata metadata, string key, object? model) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(key); Metadata = metadata; Key = key; @@ -43,20 +36,9 @@ public ValidationEntry(ModelMetadata metadata, string key, object? model) /// A delegate that will return the . public ValidationEntry(ModelMetadata metadata, string key, Func modelAccessor) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (modelAccessor == null) - { - throw new ArgumentNullException(nameof(modelAccessor)); - } + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(modelAccessor); Metadata = metadata; Key = key; diff --git a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ValueProviderFactoryContext.cs b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ValueProviderFactoryContext.cs index 0c1b9e68ae4b..5b819560c7ec 100644 --- a/src/Mvc/Mvc.Abstractions/src/ModelBinding/ValueProviderFactoryContext.cs +++ b/src/Mvc/Mvc.Abstractions/src/ModelBinding/ValueProviderFactoryContext.cs @@ -14,10 +14,7 @@ public class ValueProviderFactoryContext /// The . public ValueProviderFactoryContext(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); ActionContext = context; } diff --git a/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionExtensions.cs b/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionExtensions.cs index e0890aeae56b..69c6c570f956 100644 --- a/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionExtensions.cs +++ b/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionExtensions.cs @@ -17,10 +17,7 @@ public static class ApiDescriptionExtensions /// The property or the default value of . public static T? GetProperty(this ApiDescription apiDescription) { - if (apiDescription == null) - { - throw new ArgumentNullException(nameof(apiDescription)); - } + ArgumentNullException.ThrowIfNull(apiDescription); if (apiDescription.Properties.TryGetValue(typeof(T), out var value)) { @@ -41,10 +38,7 @@ public static class ApiDescriptionExtensions /// The value of the property. public static void SetProperty(this ApiDescription apiDescription, T value) { - if (apiDescription == null) - { - throw new ArgumentNullException(nameof(apiDescription)); - } + ArgumentNullException.ThrowIfNull(apiDescription); if (value == null) { diff --git a/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionGroupCollection.cs b/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionGroupCollection.cs index 8672e1438b81..a11f65de0482 100644 --- a/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionGroupCollection.cs +++ b/src/Mvc/Mvc.ApiExplorer/src/ApiDescriptionGroupCollection.cs @@ -15,10 +15,7 @@ public class ApiDescriptionGroupCollection /// The unique version of discovered groups. public ApiDescriptionGroupCollection(IReadOnlyList items, int version) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); Items = items; Version = version; diff --git a/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs b/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs index ffe76751eb46..4aef98aabd96 100644 --- a/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs +++ b/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs @@ -58,10 +58,7 @@ public DefaultApiDescriptionProvider( /// public void OnProvidersExecuting(ApiDescriptionProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var action in context.Actions.OfType()) { diff --git a/src/Mvc/Mvc.ApiExplorer/src/DependencyInjection/MvcApiExplorerMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.ApiExplorer/src/DependencyInjection/MvcApiExplorerMvcCoreBuilderExtensions.cs index 9aaf906a9620..8e26708c6bc8 100644 --- a/src/Mvc/Mvc.ApiExplorer/src/DependencyInjection/MvcApiExplorerMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.ApiExplorer/src/DependencyInjection/MvcApiExplorerMvcCoreBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class MvcApiExplorerMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddApiExplorer(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddApiExplorerServices(builder.Services); return builder; diff --git a/src/Mvc/Mvc.Core/src/AcceptVerbsAttribute.cs b/src/Mvc/Mvc.Core/src/AcceptVerbsAttribute.cs index 103a0f728858..f7b82d4c050d 100644 --- a/src/Mvc/Mvc.Core/src/AcceptVerbsAttribute.cs +++ b/src/Mvc/Mvc.Core/src/AcceptVerbsAttribute.cs @@ -24,10 +24,7 @@ public sealed class AcceptVerbsAttribute : Attribute, IActionHttpMethodProvider, public AcceptVerbsAttribute(string method) : this(new[] { method }) { - if (method == null) - { - throw new ArgumentNullException(nameof(method)); - } + ArgumentNullException.ThrowIfNull(method); } /// diff --git a/src/Mvc/Mvc.Core/src/AcceptedAtActionResult.cs b/src/Mvc/Mvc.Core/src/AcceptedAtActionResult.cs index a444de4a4671..e957d570b130 100644 --- a/src/Mvc/Mvc.Core/src/AcceptedAtActionResult.cs +++ b/src/Mvc/Mvc.Core/src/AcceptedAtActionResult.cs @@ -62,10 +62,7 @@ public AcceptedAtActionResult( /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/AcceptedAtRouteResult.cs b/src/Mvc/Mvc.Core/src/AcceptedAtRouteResult.cs index e7894e49b213..17358e494c10 100644 --- a/src/Mvc/Mvc.Core/src/AcceptedAtRouteResult.cs +++ b/src/Mvc/Mvc.Core/src/AcceptedAtRouteResult.cs @@ -65,10 +65,7 @@ public AcceptedAtRouteResult( /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/AcceptedResult.cs b/src/Mvc/Mvc.Core/src/AcceptedResult.cs index ebeadcf3e89f..786bc9adf7ff 100644 --- a/src/Mvc/Mvc.Core/src/AcceptedResult.cs +++ b/src/Mvc/Mvc.Core/src/AcceptedResult.cs @@ -46,10 +46,7 @@ public AcceptedResult(string? location, [ActionResultObjectValue] object? value) public AcceptedResult(Uri locationUri, [ActionResultObjectValue] object? value) : base(value) { - if (locationUri == null) - { - throw new ArgumentNullException(nameof(locationUri)); - } + ArgumentNullException.ThrowIfNull(locationUri); if (locationUri.IsAbsoluteUri) { @@ -71,10 +68,7 @@ public AcceptedResult(Uri locationUri, [ActionResultObjectValue] object? value) /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/ActionConstraints/DefaultActionConstraintProvider.cs b/src/Mvc/Mvc.Core/src/ActionConstraints/DefaultActionConstraintProvider.cs index a1883f27629c..353b08869968 100644 --- a/src/Mvc/Mvc.Core/src/ActionConstraints/DefaultActionConstraintProvider.cs +++ b/src/Mvc/Mvc.Core/src/ActionConstraints/DefaultActionConstraintProvider.cs @@ -19,10 +19,7 @@ internal sealed class DefaultActionConstraintProvider : IActionConstraintProvide /// public void OnProvidersExecuting(ActionConstraintProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); for (var i = 0; i < context.Results.Count; i++) { diff --git a/src/Mvc/Mvc.Core/src/ActionConstraints/HttpMethodActionConstraint.cs b/src/Mvc/Mvc.Core/src/ActionConstraints/HttpMethodActionConstraint.cs index 269caf003f63..f7921e0fc451 100644 --- a/src/Mvc/Mvc.Core/src/ActionConstraints/HttpMethodActionConstraint.cs +++ b/src/Mvc/Mvc.Core/src/ActionConstraints/HttpMethodActionConstraint.cs @@ -30,10 +30,7 @@ public class HttpMethodActionConstraint : IActionConstraint /// public HttpMethodActionConstraint(IEnumerable httpMethods) { - if (httpMethods == null) - { - throw new ArgumentNullException(nameof(httpMethods)); - } + ArgumentNullException.ThrowIfNull(httpMethods); var methods = new List(); @@ -61,10 +58,7 @@ public HttpMethodActionConstraint(IEnumerable httpMethods) /// public virtual bool Accept(ActionConstraintContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (_httpMethods.Count == 0) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ActionModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ActionModel.cs index 05b423a4954a..d1e40473275c 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ActionModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ActionModel.cs @@ -26,15 +26,8 @@ public ActionModel( MethodInfo actionMethod, IReadOnlyList attributes) { - if (actionMethod == null) - { - throw new ArgumentNullException(nameof(actionMethod)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(actionMethod); + ArgumentNullException.ThrowIfNull(attributes); ActionMethod = actionMethod; @@ -53,10 +46,7 @@ public ActionModel( /// The to copy. public ActionModel(ActionModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); ActionMethod = other.ActionMethod; ActionName = other.ActionName; diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ApiConventionApplicationModelConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ApiConventionApplicationModelConvention.cs index 164683ebd346..4bc92ab5e5a9 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ApiConventionApplicationModelConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ApiConventionApplicationModelConvention.cs @@ -36,10 +36,7 @@ public ApiConventionApplicationModelConvention(ProducesErrorResponseTypeAttribut /// public void Apply(ActionModel action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); if (!ShouldApply(action)) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ApiExplorerModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ApiExplorerModel.cs index cd31903ddaa0..3b6803ed725f 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ApiExplorerModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ApiExplorerModel.cs @@ -21,10 +21,7 @@ public ApiExplorerModel() /// The to copy. public ApiExplorerModel(ApiExplorerModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); GroupName = other.GroupName; IsVisible = other.IsVisible; diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelConventions.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelConventions.cs index 6ca370c14e89..530f4077f6c6 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelConventions.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelConventions.cs @@ -19,15 +19,8 @@ public static void ApplyConventions( ApplicationModel applicationModel, IEnumerable conventions) { - if (applicationModel == null) - { - throw new ArgumentNullException(nameof(applicationModel)); - } - - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(applicationModel); + ArgumentNullException.ThrowIfNull(conventions); // Conventions are applied from the outside-in to allow for scenarios where an action overrides // a controller, etc. diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelFactory.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelFactory.cs index 5d98a9b17752..c50247b9be51 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelFactory.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelFactory.cs @@ -23,15 +23,8 @@ public ApplicationModelFactory( IEnumerable applicationModelProviders, IOptions options) { - if (applicationModelProviders == null) - { - throw new ArgumentNullException(nameof(applicationModelProviders)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(applicationModelProviders); + ArgumentNullException.ThrowIfNull(options); _applicationModelProviders = applicationModelProviders.OrderBy(p => p.Order).ToArray(); _conventions = options.Value.Conventions; @@ -39,10 +32,7 @@ public ApplicationModelFactory( public ApplicationModel CreateApplicationModel(IEnumerable controllerTypes) { - if (controllerTypes == null) - { - throw new ArgumentNullException(nameof(controllerTypes)); - } + ArgumentNullException.ThrowIfNull(controllerTypes); var context = new ApplicationModelProviderContext(controllerTypes); diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelProviderContext.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelProviderContext.cs index 48f08002d61a..e3335a1f3956 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelProviderContext.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ApplicationModelProviderContext.cs @@ -16,10 +16,7 @@ public class ApplicationModelProviderContext /// The discovered controller instances. public ApplicationModelProviderContext(IEnumerable controllerTypes) { - if (controllerTypes == null) - { - throw new ArgumentNullException(nameof(controllerTypes)); - } + ArgumentNullException.ThrowIfNull(controllerTypes); ControllerTypes = controllerTypes; } diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/AttributeRouteModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/AttributeRouteModel.cs index d56f5304e085..71be5cf0eb52 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/AttributeRouteModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/AttributeRouteModel.cs @@ -30,10 +30,7 @@ public AttributeRouteModel() /// The . public AttributeRouteModel(IRouteTemplateProvider templateProvider) { - if (templateProvider == null) - { - throw new ArgumentNullException(nameof(templateProvider)); - } + ArgumentNullException.ThrowIfNull(templateProvider); Attribute = templateProvider; Template = templateProvider.Template; @@ -47,10 +44,7 @@ public AttributeRouteModel(IRouteTemplateProvider templateProvider) /// The to copy. public AttributeRouteModel(AttributeRouteModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Attribute = other.Attribute; Name = other.Name; diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs index 907756de3302..7fc65e0f67ff 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs @@ -30,10 +30,7 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) public void OnProvidersExecuting(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (_mvcOptions.EnableEndpointRouting) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ClientErrorResultFilterConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ClientErrorResultFilterConvention.cs index 34ce2ba5aec9..b271767f7bb2 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ClientErrorResultFilterConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ClientErrorResultFilterConvention.cs @@ -17,10 +17,7 @@ public class ClientErrorResultFilterConvention : IActionModelConvention /// public void Apply(ActionModel action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); if (!ShouldApply(action)) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ConsumesConstraintForFormFileParameterConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ConsumesConstraintForFormFileParameterConvention.cs index 278585fa610b..0de9d8558df6 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ConsumesConstraintForFormFileParameterConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ConsumesConstraintForFormFileParameterConvention.cs @@ -16,10 +16,7 @@ public class ConsumesConstraintForFormFileParameterConvention : IActionModelConv /// public void Apply(ActionModel action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); if (!ShouldApply(action)) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerActionDescriptorProvider.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerActionDescriptorProvider.cs index 7f4725bcad55..1559d121efae 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerActionDescriptorProvider.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerActionDescriptorProvider.cs @@ -17,15 +17,8 @@ public ControllerActionDescriptorProvider( ApplicationPartManager partManager, ApplicationModelFactory applicationModelFactory) { - if (partManager == null) - { - throw new ArgumentNullException(nameof(partManager)); - } - - if (applicationModelFactory == null) - { - throw new ArgumentNullException(nameof(applicationModelFactory)); - } + ArgumentNullException.ThrowIfNull(partManager); + ArgumentNullException.ThrowIfNull(applicationModelFactory); _partManager = partManager; _applicationModelFactory = applicationModelFactory; @@ -36,10 +29,7 @@ public ControllerActionDescriptorProvider( /// public void OnProvidersExecuting(ActionDescriptorProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var descriptor in GetDescriptors()) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerModel.cs index 1eb8dae6e54e..f3915ee6fe56 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ControllerModel.cs @@ -25,15 +25,8 @@ public ControllerModel( TypeInfo controllerType, IReadOnlyList attributes) { - if (controllerType == null) - { - throw new ArgumentNullException(nameof(controllerType)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(controllerType); + ArgumentNullException.ThrowIfNull(attributes); ControllerType = controllerType; @@ -53,10 +46,7 @@ public ControllerModel( /// The other controller model. public ControllerModel(ControllerModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); ControllerName = other.ControllerName; ControllerType = other.ControllerType; diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/DefaultApplicationModelProvider.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/DefaultApplicationModelProvider.cs index cfce701f8f21..829ceef8f59b 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/DefaultApplicationModelProvider.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/DefaultApplicationModelProvider.cs @@ -41,10 +41,7 @@ public DefaultApplicationModelProvider( /// public void OnProvidersExecuting(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var filter in _mvcOptions.Filters) { @@ -110,10 +107,7 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) /// A for the given . internal static ControllerModel CreateControllerModel(TypeInfo typeInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); // For attribute routes on a controller, we want to support 'overriding' routes on a derived // class. So we need to walk up the hierarchy looking for the first class to define routes. @@ -215,10 +209,7 @@ internal static ControllerModel CreateControllerModel(TypeInfo typeInfo) /// A for the given . internal PropertyModel CreatePropertyModel(PropertyInfo propertyInfo) { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } + ArgumentNullException.ThrowIfNull(propertyInfo); var attributes = propertyInfo.GetCustomAttributes(inherit: true); @@ -265,15 +256,8 @@ internal PropertyModel CreatePropertyModel(PropertyInfo propertyInfo) TypeInfo typeInfo, MethodInfo methodInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } - - if (methodInfo == null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); + ArgumentNullException.ThrowIfNull(methodInfo); if (!IsAction(typeInfo, methodInfo)) { @@ -392,15 +376,8 @@ private string CanonicalizeActionName(string actionName) /// internal static bool IsAction(TypeInfo typeInfo, MethodInfo methodInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } - - if (methodInfo == null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); + ArgumentNullException.ThrowIfNull(methodInfo); // The SpecialName bit is set to flag members that are treated in a special way by some compilers // (such as property accessors and operator overloading methods). @@ -456,10 +433,7 @@ internal static bool IsAction(TypeInfo typeInfo, MethodInfo methodInfo) /// A for the given . internal ParameterModel CreateParameterModel(ParameterInfo parameterInfo) { - if (parameterInfo == null) - { - throw new ArgumentNullException(nameof(parameterInfo)); - } + ArgumentNullException.ThrowIfNull(parameterInfo); var attributes = parameterInfo.GetCustomAttributes(inherit: true); diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/InferParameterBindingInfoConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/InferParameterBindingInfoConvention.cs index 6642445e37de..f84b8a6bc854 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/InferParameterBindingInfoConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/InferParameterBindingInfoConvention.cs @@ -66,10 +66,7 @@ public InferParameterBindingInfoConvention( /// The . public void Apply(ActionModel action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); if (!ShouldApply(action)) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/InvalidModelStateFilterConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/InvalidModelStateFilterConvention.cs index ac536822f6de..fb91bfa13d80 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/InvalidModelStateFilterConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/InvalidModelStateFilterConvention.cs @@ -17,10 +17,7 @@ public class InvalidModelStateFilterConvention : IActionModelConvention /// public void Apply(ActionModel action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); if (!ShouldApply(action)) { diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModel.cs index f619e7a60f12..192e95dfcc75 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModel.cs @@ -33,10 +33,7 @@ public ParameterModel( public ParameterModel(ParameterModel other) : base(other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Action = other.Action; ParameterInfo = other.ParameterInfo; diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModelBase.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModelBase.cs index e069393069f7..411a8c9bca97 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModelBase.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/ParameterModelBase.cs @@ -34,10 +34,7 @@ protected ParameterModelBase( /// The other instance to copy protected ParameterModelBase(ParameterModelBase other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); ParameterType = other.ParameterType; Attributes = new List(other.Attributes); diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/PropertyModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/PropertyModel.cs index 76ee8cbe3f6b..9d5412b8652d 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/PropertyModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/PropertyModel.cs @@ -33,10 +33,7 @@ public PropertyModel( public PropertyModel(PropertyModel other) : base(other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Controller = other.Controller; BindingInfo = other.BindingInfo == null ? null : new BindingInfo(other.BindingInfo); diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/RouteTokenTransformerConvention.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/RouteTokenTransformerConvention.cs index b6a9c94346ac..a933d658d100 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/RouteTokenTransformerConvention.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/RouteTokenTransformerConvention.cs @@ -20,10 +20,7 @@ public class RouteTokenTransformerConvention : IActionModelConvention /// The to use with attribute routing token replacement. public RouteTokenTransformerConvention(IOutboundParameterTransformer parameterTransformer) { - if (parameterTransformer == null) - { - throw new ArgumentNullException(nameof(parameterTransformer)); - } + ArgumentNullException.ThrowIfNull(parameterTransformer); _parameterTransformer = parameterTransformer; } diff --git a/src/Mvc/Mvc.Core/src/ApplicationModels/SelectorModel.cs b/src/Mvc/Mvc.Core/src/ApplicationModels/SelectorModel.cs index 9c244f337573..ef04f4b43f22 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationModels/SelectorModel.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationModels/SelectorModel.cs @@ -25,10 +25,7 @@ public SelectorModel() /// The to copy from. public SelectorModel(SelectorModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); ActionConstraints = new List(other.ActionConstraints); EndpointMetadata = new List(other.EndpointMetadata); diff --git a/src/Mvc/Mvc.Core/src/ApplicationParts/ApplicationPartFactory.cs b/src/Mvc/Mvc.Core/src/ApplicationParts/ApplicationPartFactory.cs index 3ffc5d6ae873..852eff99cc89 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationParts/ApplicationPartFactory.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationParts/ApplicationPartFactory.cs @@ -34,10 +34,7 @@ public abstract class ApplicationPartFactory /// An instance of . public static ApplicationPartFactory GetApplicationPartFactory(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); var provideAttribute = assembly.GetCustomAttribute(); if (provideAttribute == null) diff --git a/src/Mvc/Mvc.Core/src/ApplicationParts/DefaultApplicationPartFactory.cs b/src/Mvc/Mvc.Core/src/ApplicationParts/DefaultApplicationPartFactory.cs index 3d1ecd02c5e2..41ed9f059a99 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationParts/DefaultApplicationPartFactory.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationParts/DefaultApplicationPartFactory.cs @@ -25,10 +25,7 @@ public class DefaultApplicationPartFactory : ApplicationPartFactory /// The sequence of instances. public static IEnumerable GetDefaultApplicationParts(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); yield return new AssemblyPart(assembly); } diff --git a/src/Mvc/Mvc.Core/src/ApplicationParts/RelatedAssemblyAttribute.cs b/src/Mvc/Mvc.Core/src/ApplicationParts/RelatedAssemblyAttribute.cs index 6de996f61b5c..09d1e414446c 100644 --- a/src/Mvc/Mvc.Core/src/ApplicationParts/RelatedAssemblyAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ApplicationParts/RelatedAssemblyAttribute.cs @@ -41,10 +41,7 @@ public RelatedAssemblyAttribute(string assemblyFileName) /// Related instances. public static IReadOnlyList GetRelatedAssemblies(Assembly assembly, bool throwOnError) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); var loadContext = AssemblyLoadContext.GetLoadContext(assembly) ?? AssemblyLoadContext.Default; return GetRelatedAssemblies(assembly, throwOnError, File.Exists, new AssemblyLoadContextWrapper(loadContext)); @@ -56,10 +53,7 @@ internal static IReadOnlyList GetRelatedAssemblies( Func fileExists, AssemblyLoadContextWrapper assemblyLoadContext) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); // MVC will specifically look for related parts in the same physical directory as the assembly. // No-op if the assembly does not have a location. diff --git a/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs b/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs index 455c7b31e1e8..de13a9a40982 100644 --- a/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs +++ b/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs @@ -38,10 +38,7 @@ public AuthorizeFilter() /// Authorization policy to be used. public AuthorizeFilter(AuthorizationPolicy policy) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(policy); Policy = policy; } @@ -54,10 +51,7 @@ public AuthorizeFilter(AuthorizationPolicy policy) public AuthorizeFilter(IAuthorizationPolicyProvider policyProvider, IEnumerable authorizeData) : this(authorizeData) { - if (policyProvider == null) - { - throw new ArgumentNullException(nameof(policyProvider)); - } + ArgumentNullException.ThrowIfNull(policyProvider); PolicyProvider = policyProvider; } @@ -68,10 +62,7 @@ public AuthorizeFilter(IAuthorizationPolicyProvider policyProvider, IEnumerable< /// The to combine into an . public AuthorizeFilter(IEnumerable authorizeData) { - if (authorizeData == null) - { - throw new ArgumentNullException(nameof(authorizeData)); - } + ArgumentNullException.ThrowIfNull(authorizeData); AuthorizeData = authorizeData; } @@ -167,10 +158,7 @@ internal async Task GetEffectivePolicyAsync(AuthorizationFi /// public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.IsEffectivePolicy(this)) { diff --git a/src/Mvc/Mvc.Core/src/BadRequestObjectResult.cs b/src/Mvc/Mvc.Core/src/BadRequestObjectResult.cs index 7d9fead930e5..d1908daf3ec3 100644 --- a/src/Mvc/Mvc.Core/src/BadRequestObjectResult.cs +++ b/src/Mvc/Mvc.Core/src/BadRequestObjectResult.cs @@ -32,10 +32,7 @@ public BadRequestObjectResult([ActionResultObjectValue] object? error) public BadRequestObjectResult([ActionResultObjectValue] ModelStateDictionary modelState) : base(new SerializableError(modelState)) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); StatusCode = DefaultStatusCode; } diff --git a/src/Mvc/Mvc.Core/src/Builder/ControllerActionEndpointConventionBuilder.cs b/src/Mvc/Mvc.Core/src/Builder/ControllerActionEndpointConventionBuilder.cs index 20e4a9818e0b..58fbea9616ed 100644 --- a/src/Mvc/Mvc.Core/src/Builder/ControllerActionEndpointConventionBuilder.cs +++ b/src/Mvc/Mvc.Core/src/Builder/ControllerActionEndpointConventionBuilder.cs @@ -29,10 +29,7 @@ internal ControllerActionEndpointConventionBuilder(object @lock, ListThe convention to add to the builder. public void Add(Action convention) { - if (convention == null) - { - throw new ArgumentNullException(nameof(convention)); - } + ArgumentNullException.ThrowIfNull(convention); // The lock is shared with the data source. We want to lock here // to avoid mutating this list while its read in the data source. diff --git a/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs b/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs index cfec6bb72590..833479861bef 100644 --- a/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs @@ -24,10 +24,7 @@ public static class ControllerEndpointRouteBuilderExtensions /// An for endpoints associated with controller actions. public static ControllerActionEndpointConventionBuilder MapControllers(this IEndpointRouteBuilder endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureControllerServices(endpoints); @@ -44,10 +41,7 @@ public static ControllerActionEndpointConventionBuilder MapControllers(this IEnd /// public static ControllerActionEndpointConventionBuilder MapDefaultControllerRoute(this IEndpointRouteBuilder endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureControllerServices(endpoints); @@ -91,10 +85,7 @@ public static ControllerActionEndpointConventionBuilder MapControllerRoute( object? constraints = null, object? dataTokens = null) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureControllerServices(endpoints); @@ -140,10 +131,7 @@ public static ControllerActionEndpointConventionBuilder MapAreaControllerRoute( object? constraints = null, object? dataTokens = null) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); if (string.IsNullOrEmpty(areaName)) { @@ -194,20 +182,9 @@ public static IEndpointConventionBuilder MapFallbackToController( string action, string controller) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); EnsureControllerServices(endpoints); @@ -268,25 +245,10 @@ public static IEndpointConventionBuilder MapFallbackToController( string action, string controller) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); EnsureControllerServices(endpoints); @@ -344,20 +306,9 @@ public static IEndpointConventionBuilder MapFallbackToAreaController( string controller, string area) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); EnsureControllerServices(endpoints); @@ -420,25 +371,10 @@ public static IEndpointConventionBuilder MapFallbackToAreaController( string controller, string area) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); EnsureControllerServices(endpoints); @@ -479,10 +415,7 @@ public static IEndpointConventionBuilder MapFallbackToAreaController( public static void MapDynamicControllerRoute(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern) where TTransformer : DynamicRouteValueTransformer { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); MapDynamicControllerRoute(endpoints, pattern, state: null); } @@ -509,10 +442,7 @@ public static void MapDynamicControllerRoute(this IEndpointRouteBu public static void MapDynamicControllerRoute(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, object? state) where TTransformer : DynamicRouteValueTransformer { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureControllerServices(endpoints); @@ -547,10 +477,7 @@ public static void MapDynamicControllerRoute(this IEndpointRouteBu public static void MapDynamicControllerRoute(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, object state, int order) where TTransformer : DynamicRouteValueTransformer { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureControllerServices(endpoints); diff --git a/src/Mvc/Mvc.Core/src/Builder/MvcApplicationBuilderExtensions.cs b/src/Mvc/Mvc.Core/src/Builder/MvcApplicationBuilderExtensions.cs index 59303863695a..d22124d56e1c 100644 --- a/src/Mvc/Mvc.Core/src/Builder/MvcApplicationBuilderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/Builder/MvcApplicationBuilderExtensions.cs @@ -24,10 +24,7 @@ public static class MvcApplicationBuilderExtensions /// . public static IApplicationBuilder UseMvc(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMvc(routes => { @@ -43,10 +40,7 @@ public static IApplicationBuilder UseMvc(this IApplicationBuilder app) /// A reference to this instance after the operation has completed. public static IApplicationBuilder UseMvcWithDefaultRoute(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMvc(routes => { @@ -66,15 +60,8 @@ public static IApplicationBuilder UseMvc( this IApplicationBuilder app, Action configureRoutes) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (configureRoutes == null) - { - throw new ArgumentNullException(nameof(configureRoutes)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(configureRoutes); VerifyMvcIsRegistered(app); diff --git a/src/Mvc/Mvc.Core/src/Builder/MvcAreaRouteBuilderExtensions.cs b/src/Mvc/Mvc.Core/src/Builder/MvcAreaRouteBuilderExtensions.cs index 7461bc9b2558..2c65c055a686 100644 --- a/src/Mvc/Mvc.Core/src/Builder/MvcAreaRouteBuilderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/Builder/MvcAreaRouteBuilderExtensions.cs @@ -118,10 +118,7 @@ public static IRouteBuilder MapAreaRoute( object? constraints, object? dataTokens) { - if (routeBuilder == null) - { - throw new ArgumentNullException(nameof(routeBuilder)); - } + ArgumentNullException.ThrowIfNull(routeBuilder); if (string.IsNullOrEmpty(areaName)) { diff --git a/src/Mvc/Mvc.Core/src/ChallengeResult.cs b/src/Mvc/Mvc.Core/src/ChallengeResult.cs index 2fc451faa188..affa9d116e46 100644 --- a/src/Mvc/Mvc.Core/src/ChallengeResult.cs +++ b/src/Mvc/Mvc.Core/src/ChallengeResult.cs @@ -90,10 +90,7 @@ public ChallengeResult(IList authenticationSchemes, AuthenticationProper /// public override async Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var httpContext = context.HttpContext; var loggerFactory = httpContext.RequestServices.GetRequiredService(); diff --git a/src/Mvc/Mvc.Core/src/ConflictObjectResult.cs b/src/Mvc/Mvc.Core/src/ConflictObjectResult.cs index 2b3518d0c119..d906d82978d4 100644 --- a/src/Mvc/Mvc.Core/src/ConflictObjectResult.cs +++ b/src/Mvc/Mvc.Core/src/ConflictObjectResult.cs @@ -32,10 +32,7 @@ public ConflictObjectResult([ActionResultObjectValue] object? error) public ConflictObjectResult([ActionResultObjectValue] ModelStateDictionary modelState) : base(new SerializableError(modelState)) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); StatusCode = DefaultStatusCode; } diff --git a/src/Mvc/Mvc.Core/src/ConsumesAttribute.cs b/src/Mvc/Mvc.Core/src/ConsumesAttribute.cs index c071bf561b2c..db60690d461a 100644 --- a/src/Mvc/Mvc.Core/src/ConsumesAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ConsumesAttribute.cs @@ -38,10 +38,7 @@ public class ConsumesAttribute : /// public ConsumesAttribute(string contentType, params string[] otherContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); // We want to ensure that the given provided content types are valid values, so // we validate them using the semantics of MediaTypeHeaderValue. @@ -64,10 +61,7 @@ public ConsumesAttribute(string contentType, params string[] otherContentTypes) /// public ConsumesAttribute(Type requestType, string contentType, params string[] otherContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); // We want to ensure that the given provided content types are valid values, so // we validate them using the semantics of MediaTypeHeaderValue. @@ -111,10 +105,7 @@ public ConsumesAttribute(Type requestType, string contentType, params string[] o /// public void OnResourceExecuting(ResourceExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Only execute if the current filter is the one which is closest to the action. // Ignore all other filters. This is to ensure we have a overriding behavior. @@ -151,10 +142,7 @@ private bool IsSubsetOfAnyContentType(string requestMediaType) /// public void OnResourceExecuted(ResourceExecutedContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); } /// diff --git a/src/Mvc/Mvc.Core/src/ContentResult.cs b/src/Mvc/Mvc.Core/src/ContentResult.cs index 8354ab321657..584a9fd60357 100644 --- a/src/Mvc/Mvc.Core/src/ContentResult.cs +++ b/src/Mvc/Mvc.Core/src/ContentResult.cs @@ -30,10 +30,7 @@ public class ContentResult : ActionResult, IStatusCodeActionResult /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/ControllerBase.cs b/src/Mvc/Mvc.Core/src/ControllerBase.cs index 56f5de6df09f..8b2510c55b28 100644 --- a/src/Mvc/Mvc.Core/src/ControllerBase.cs +++ b/src/Mvc/Mvc.Core/src/ControllerBase.cs @@ -78,10 +78,7 @@ public ControllerContext ControllerContext } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _controllerContext = value; } @@ -103,10 +100,7 @@ public IModelMetadataProvider MetadataProvider } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _metadataProvider = value; } @@ -128,10 +122,7 @@ public IModelBinderFactory ModelBinderFactory } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _modelBinderFactory = value; } @@ -154,10 +145,7 @@ public IUrlHelper Url } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _url = value; } @@ -179,10 +167,7 @@ public IObjectModelValidator ObjectValidator } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _objectValidator = value; } @@ -204,10 +189,7 @@ public ProblemDetailsFactory ProblemDetailsFactory } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _problemDetailsFactory = value; } @@ -1057,10 +1039,7 @@ public virtual RedirectToPageResult RedirectToPagePreserveMethod( object? routeValues = null, string? fragment = null) { - if (pageName == null) - { - throw new ArgumentNullException(nameof(pageName)); - } + ArgumentNullException.ThrowIfNull(pageName); return new RedirectToPageResult( pageName: pageName, @@ -1088,10 +1067,7 @@ public virtual RedirectToPageResult RedirectToPagePermanentPreserveMethod( object? routeValues = null, string? fragment = null) { - if (pageName == null) - { - throw new ArgumentNullException(nameof(pageName)); - } + ArgumentNullException.ThrowIfNull(pageName); return new RedirectToPageResult( pageName: pageName, @@ -1807,10 +1783,7 @@ public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] objec [NonAction] public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] ModelStateDictionary modelState) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); return new BadRequestObjectResult(modelState); } @@ -1840,10 +1813,7 @@ public virtual UnprocessableEntityObjectResult UnprocessableEntity([ActionResult [NonAction] public virtual UnprocessableEntityObjectResult UnprocessableEntity([ActionResultObjectValue] ModelStateDictionary modelState) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); return new UnprocessableEntityObjectResult(modelState); } @@ -1929,10 +1899,7 @@ public virtual ObjectResult Problem( [DefaultStatusCode(StatusCodes.Status400BadRequest)] public virtual ActionResult ValidationProblem([ActionResultObjectValue] ValidationProblemDetails descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); return new BadRequestObjectResult(descriptor); } @@ -2021,7 +1988,7 @@ public virtual ActionResult ValidationProblem( /// /// Creates a object that produces a response. - /// + /// /// The created for the response. [NonAction] public virtual CreatedResult Created() @@ -2147,10 +2114,7 @@ public virtual AcceptedResult Accepted([ActionResultObjectValue] object? value) [NonAction] public virtual AcceptedResult Accepted(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); return new AcceptedResult(locationUri: uri, value: null); } @@ -2184,10 +2148,7 @@ public virtual AcceptedResult Accepted(string? uri, [ActionResultObjectValue] ob [NonAction] public virtual AcceptedResult Accepted(Uri uri, [ActionResultObjectValue] object? value) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); return new AcceptedResult(locationUri: uri, value: value); } @@ -2521,10 +2482,7 @@ public virtual Task TryUpdateModelAsync( TModel model) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryUpdateModelAsync(model, prefix: string.Empty); } @@ -2544,15 +2502,8 @@ public virtual async Task TryUpdateModelAsync( string prefix) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(prefix); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories); if (!success) @@ -2580,20 +2531,9 @@ public virtual Task TryUpdateModelAsync( IValueProvider valueProvider) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(valueProvider); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -2623,15 +2563,8 @@ public async Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(includeExpressions); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories); if (!success) @@ -2667,15 +2600,8 @@ public async Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(propertyFilter); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories); if (!success) @@ -2714,20 +2640,9 @@ public Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(includeExpressions); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -2759,20 +2674,9 @@ public Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -2800,15 +2704,8 @@ public virtual async Task TryUpdateModelAsync( Type modelType, string prefix) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(ControllerContext, ControllerContext.ValueProviderFactories); if (!success) @@ -2846,25 +2743,10 @@ public Task TryUpdateModelAsync( IValueProvider valueProvider, Func propertyFilter) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -2887,10 +2769,7 @@ public Task TryUpdateModelAsync( public virtual bool TryValidateModel( object model) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryValidateModel(model, prefix: null); } @@ -2907,10 +2786,7 @@ public virtual bool TryValidateModel( object model, string? prefix) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); ObjectValidator.Validate( ControllerContext, diff --git a/src/Mvc/Mvc.Core/src/ControllerContext.cs b/src/Mvc/Mvc.Core/src/ControllerContext.cs index cf6346f3a0e2..de12047af136 100644 --- a/src/Mvc/Mvc.Core/src/ControllerContext.cs +++ b/src/Mvc/Mvc.Core/src/ControllerContext.cs @@ -80,10 +80,7 @@ public virtual IList ValueProviderFactories } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _valueProviderFactories = value; } diff --git a/src/Mvc/Mvc.Core/src/Controllers/ControllerActionDescriptor.cs b/src/Mvc/Mvc.Core/src/Controllers/ControllerActionDescriptor.cs index d8a9ee154aa3..365fa57135b5 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/ControllerActionDescriptor.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/ControllerActionDescriptor.cs @@ -62,10 +62,7 @@ public override string? DisplayName set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); base.DisplayName = value; } diff --git a/src/Mvc/Mvc.Core/src/Controllers/ControllerActivatorProvider.cs b/src/Mvc/Mvc.Core/src/Controllers/ControllerActivatorProvider.cs index 3d1eecc55a1f..4805c7e2f54e 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/ControllerActivatorProvider.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/ControllerActivatorProvider.cs @@ -25,10 +25,7 @@ public class ControllerActivatorProvider : IControllerActivatorProvider /// A which is delegated to when not the default implementation. public ControllerActivatorProvider(IControllerActivator controllerActivator) { - if (controllerActivator == null) - { - throw new ArgumentNullException(nameof(controllerActivator)); - } + ArgumentNullException.ThrowIfNull(controllerActivator); // Compat: Delegate to controllerActivator if it's not the default implementation. if (controllerActivator.GetType() != typeof(DefaultControllerActivator)) @@ -42,10 +39,7 @@ public ControllerActivatorProvider(IControllerActivator controllerActivator) /// public Func CreateActivator(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); var controllerType = descriptor.ControllerTypeInfo?.AsType(); if (controllerType == null) @@ -68,10 +62,7 @@ public Func CreateActivator(ControllerActionDescripto /// public Action? CreateReleaser(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); if (_controllerActivatorRelease != null) { @@ -89,10 +80,7 @@ public Func CreateActivator(ControllerActionDescripto /// public Func? CreateAsyncReleaser(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); if (_controllerActivatorReleaseAsync != null) { @@ -114,20 +102,14 @@ public Func CreateActivator(ControllerActionDescripto private static void Dispose(ControllerContext context, object controller) { - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(controller); ((IDisposable)controller).Dispose(); } private static ValueTask DisposeAsync(ControllerContext context, object controller) { - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(controller); return ((IAsyncDisposable)controller).DisposeAsync(); } diff --git a/src/Mvc/Mvc.Core/src/Controllers/ControllerBinderDelegateProvider.cs b/src/Mvc/Mvc.Core/src/Controllers/ControllerBinderDelegateProvider.cs index 699980543986..e7fae8222bc1 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/ControllerBinderDelegateProvider.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/ControllerBinderDelegateProvider.cs @@ -18,30 +18,11 @@ internal static class ControllerBinderDelegateProvider ControllerActionDescriptor actionDescriptor, MvcOptions mvcOptions) { - if (parameterBinder == null) - { - throw new ArgumentNullException(nameof(parameterBinder)); - } - - if (modelBinderFactory == null) - { - throw new ArgumentNullException(nameof(modelBinderFactory)); - } - - if (modelMetadataProvider == null) - { - throw new ArgumentNullException(nameof(modelMetadataProvider)); - } - - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } - - if (mvcOptions == null) - { - throw new ArgumentNullException(nameof(mvcOptions)); - } + ArgumentNullException.ThrowIfNull(parameterBinder); + ArgumentNullException.ThrowIfNull(modelBinderFactory); + ArgumentNullException.ThrowIfNull(modelMetadataProvider); + ArgumentNullException.ThrowIfNull(actionDescriptor); + ArgumentNullException.ThrowIfNull(mvcOptions); var parameterBindingInfo = GetParameterBindingInfo( modelBinderFactory, diff --git a/src/Mvc/Mvc.Core/src/Controllers/ControllerFactoryProvider.cs b/src/Mvc/Mvc.Core/src/Controllers/ControllerFactoryProvider.cs index eb3591f159e1..613f64e44575 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/ControllerFactoryProvider.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/ControllerFactoryProvider.cs @@ -19,15 +19,8 @@ public ControllerFactoryProvider( IControllerFactory controllerFactory, IEnumerable propertyActivators) { - if (activatorProvider == null) - { - throw new ArgumentNullException(nameof(activatorProvider)); - } - - if (controllerFactory == null) - { - throw new ArgumentNullException(nameof(controllerFactory)); - } + ArgumentNullException.ThrowIfNull(activatorProvider); + ArgumentNullException.ThrowIfNull(controllerFactory); _activatorProvider = activatorProvider; @@ -44,10 +37,7 @@ public ControllerFactoryProvider( public Func CreateControllerFactory(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); var controllerType = descriptor.ControllerTypeInfo?.AsType(); if (controllerType == null) @@ -82,10 +72,7 @@ object CreateController(ControllerContext controllerContext) public Action? CreateControllerReleaser(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); var controllerType = descriptor.ControllerTypeInfo?.AsType(); if (controllerType == null) @@ -106,10 +93,7 @@ object CreateController(ControllerContext controllerContext) public Func? CreateAsyncControllerReleaser(ControllerActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); var controllerType = descriptor.ControllerTypeInfo?.AsType(); if (controllerType == null) diff --git a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerActivator.cs b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerActivator.cs index 22a5d8cc7059..34d5e09c3681 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerActivator.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerActivator.cs @@ -19,10 +19,7 @@ internal sealed class DefaultControllerActivator : IControllerActivator /// The . public DefaultControllerActivator(ITypeActivatorCache typeActivatorCache) { - if (typeActivatorCache == null) - { - throw new ArgumentNullException(nameof(typeActivatorCache)); - } + ArgumentNullException.ThrowIfNull(typeActivatorCache); _typeActivatorCache = typeActivatorCache; } @@ -30,10 +27,7 @@ public DefaultControllerActivator(ITypeActivatorCache typeActivatorCache) /// public object Create(ControllerContext controllerContext) { - if (controllerContext == null) - { - throw new ArgumentNullException(nameof(controllerContext)); - } + ArgumentNullException.ThrowIfNull(controllerContext); if (controllerContext.ActionDescriptor == null) { @@ -58,15 +52,8 @@ public object Create(ControllerContext controllerContext) /// public void Release(ControllerContext context, object controller) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(controller); if (controller is IDisposable disposable) { @@ -76,15 +63,8 @@ public void Release(ControllerContext context, object controller) public ValueTask ReleaseAsync(ControllerContext context, object controller) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(controller); if (controller is IAsyncDisposable asyncDisposable) { diff --git a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerFactory.cs b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerFactory.cs index 32e1c0028020..7b43eae2c178 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerFactory.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerFactory.cs @@ -28,15 +28,8 @@ public DefaultControllerFactory( IControllerActivator controllerActivator, IEnumerable propertyActivators) { - if (controllerActivator == null) - { - throw new ArgumentNullException(nameof(controllerActivator)); - } - - if (propertyActivators == null) - { - throw new ArgumentNullException(nameof(propertyActivators)); - } + ArgumentNullException.ThrowIfNull(controllerActivator); + ArgumentNullException.ThrowIfNull(propertyActivators); _controllerActivator = controllerActivator; _propertyActivators = propertyActivators.ToArray(); @@ -45,10 +38,7 @@ public DefaultControllerFactory( /// public object CreateController(ControllerContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ActionDescriptor == null) { @@ -69,30 +59,16 @@ public object CreateController(ControllerContext context) /// public void ReleaseController(ControllerContext context, object controller) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(controller); _controllerActivator.Release(context, controller); } public ValueTask ReleaseControllerAsync(ControllerContext context, object controller) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(controller); return _controllerActivator.ReleaseAsync(context, controller); } diff --git a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerPropertyActivator.cs b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerPropertyActivator.cs index 3c128aec964c..a2981d5b82f2 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerPropertyActivator.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/DefaultControllerPropertyActivator.cs @@ -32,10 +32,7 @@ public void Activate(ControllerContext context, object controller) public Action GetActivatorDelegate(ControllerActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); var controllerType = actionDescriptor.ControllerTypeInfo?.AsType(); if (controllerType == null) diff --git a/src/Mvc/Mvc.Core/src/Controllers/ServiceBasedControllerActivator.cs b/src/Mvc/Mvc.Core/src/Controllers/ServiceBasedControllerActivator.cs index 498fd46dfe13..fd778a035f4a 100644 --- a/src/Mvc/Mvc.Core/src/Controllers/ServiceBasedControllerActivator.cs +++ b/src/Mvc/Mvc.Core/src/Controllers/ServiceBasedControllerActivator.cs @@ -14,10 +14,7 @@ public class ServiceBasedControllerActivator : IControllerActivator /// public object Create(ControllerContext actionContext) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } + ArgumentNullException.ThrowIfNull(actionContext); var controllerType = actionContext.ActionDescriptor.ControllerTypeInfo.AsType(); diff --git a/src/Mvc/Mvc.Core/src/CreatedAtActionResult.cs b/src/Mvc/Mvc.Core/src/CreatedAtActionResult.cs index e21dba220755..5eaa307171af 100644 --- a/src/Mvc/Mvc.Core/src/CreatedAtActionResult.cs +++ b/src/Mvc/Mvc.Core/src/CreatedAtActionResult.cs @@ -62,10 +62,7 @@ public CreatedAtActionResult( /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/CreatedAtRouteResult.cs b/src/Mvc/Mvc.Core/src/CreatedAtRouteResult.cs index 2d2c545e26b2..928dac61cef9 100644 --- a/src/Mvc/Mvc.Core/src/CreatedAtRouteResult.cs +++ b/src/Mvc/Mvc.Core/src/CreatedAtRouteResult.cs @@ -65,10 +65,7 @@ public CreatedAtRouteResult( /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/CreatedResult.cs b/src/Mvc/Mvc.Core/src/CreatedResult.cs index 1ebf9b046293..dab4c7d4f83d 100644 --- a/src/Mvc/Mvc.Core/src/CreatedResult.cs +++ b/src/Mvc/Mvc.Core/src/CreatedResult.cs @@ -77,10 +77,7 @@ public string? Location /// public override void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); base.OnFormatting(context); diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/ApiBehaviorOptionsSetup.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/ApiBehaviorOptionsSetup.cs index 38c956123523..5f3d4f6012be 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/ApiBehaviorOptionsSetup.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/ApiBehaviorOptionsSetup.cs @@ -14,10 +14,7 @@ internal sealed class ApiBehaviorOptionsSetup : IConfigureOptions { diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/ApplicationModelConventionExtensions.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/ApplicationModelConventionExtensions.cs index 2a819780d5b2..98df4674f7ac 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/ApplicationModelConventionExtensions.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/ApplicationModelConventionExtensions.cs @@ -19,10 +19,7 @@ public static class ApplicationModelConventionExtensions public static void RemoveType(this IList list) where TApplicationModelConvention : IApplicationModelConvention { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); RemoveType(list, typeof(TApplicationModelConvention)); } @@ -34,15 +31,8 @@ public static void RemoveType(this IListThe type to remove. public static void RemoveType(this IList list, Type type) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(type); for (var i = list.Count - 1; i >= 0; i--) { @@ -65,15 +55,8 @@ public static void Add( this IList conventions, IControllerModelConvention controllerModelConvention) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (controllerModelConvention == null) - { - throw new ArgumentNullException(nameof(controllerModelConvention)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(controllerModelConvention); conventions.Add(new ControllerApplicationModelConvention(controllerModelConvention)); } @@ -89,15 +72,8 @@ public static void Add( this IList conventions, IActionModelConvention actionModelConvention) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (actionModelConvention == null) - { - throw new ArgumentNullException(nameof(actionModelConvention)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(actionModelConvention); conventions.Add(new ActionApplicationModelConvention(actionModelConvention)); } @@ -113,15 +89,8 @@ public static void Add( this IList conventions, IParameterModelConvention parameterModelConvention) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (parameterModelConvention == null) - { - throw new ArgumentNullException(nameof(parameterModelConvention)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(parameterModelConvention); conventions.Add(new ParameterApplicationModelConvention(parameterModelConvention)); } @@ -137,15 +106,8 @@ public static void Add( this IList conventions, IParameterModelBaseConvention parameterModelConvention) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (parameterModelConvention == null) - { - throw new ArgumentNullException(nameof(parameterModelConvention)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(parameterModelConvention); conventions.Add(new ParameterBaseApplicationModelConvention(parameterModelConvention)); } @@ -162,10 +124,7 @@ public ParameterApplicationModelConvention(IParameterModelConvention parameterMo /// public void Apply(ApplicationModel application) { - if (application == null) - { - throw new ArgumentNullException(nameof(application)); - } + ArgumentNullException.ThrowIfNull(application); // Create copies of collections of controllers, actions and parameters as users could modify // these collections from within the convention itself. @@ -198,18 +157,12 @@ public ParameterBaseApplicationModelConvention(IParameterModelBaseConvention par /// public void Apply(ApplicationModel application) { - if (application == null) - { - throw new ArgumentNullException(nameof(application)); - } + ArgumentNullException.ThrowIfNull(application); } void IParameterModelBaseConvention.Apply(ParameterModelBase parameterModel) { - if (parameterModel == null) - { - throw new ArgumentNullException(nameof(parameterModel)); - } + ArgumentNullException.ThrowIfNull(parameterModel); _parameterBaseModelConvention.Apply(parameterModel); } @@ -221,10 +174,7 @@ private sealed class ActionApplicationModelConvention : IApplicationModelConvent public ActionApplicationModelConvention(IActionModelConvention actionModelConvention) { - if (actionModelConvention == null) - { - throw new ArgumentNullException(nameof(actionModelConvention)); - } + ArgumentNullException.ThrowIfNull(actionModelConvention); _actionModelConvention = actionModelConvention; } @@ -232,10 +182,7 @@ public ActionApplicationModelConvention(IActionModelConvention actionModelConven /// public void Apply(ApplicationModel application) { - if (application == null) - { - throw new ArgumentNullException(nameof(application)); - } + ArgumentNullException.ThrowIfNull(application); // Create copies of collections of controllers, actions and parameters as users could modify // these collections from within the convention itself. @@ -257,10 +204,7 @@ private sealed class ControllerApplicationModelConvention : IApplicationModelCon public ControllerApplicationModelConvention(IControllerModelConvention controllerConvention) { - if (controllerConvention == null) - { - throw new ArgumentNullException(nameof(controllerConvention)); - } + ArgumentNullException.ThrowIfNull(controllerConvention); _controllerModelConvention = controllerConvention; } @@ -268,10 +212,7 @@ public ControllerApplicationModelConvention(IControllerModelConvention controlle /// public void Apply(ApplicationModel application) { - if (application == null) - { - throw new ArgumentNullException(nameof(application)); - } + ArgumentNullException.ThrowIfNull(application); var controllers = application.Controllers.ToArray(); foreach (var controller in controllers) diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcBuilder.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcBuilder.cs index 16f78615352b..e77486de99f5 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcBuilder.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcBuilder.cs @@ -17,15 +17,8 @@ internal sealed class MvcBuilder : IMvcBuilder /// The of the application. public MvcBuilder(IServiceCollection services, ApplicationPartManager manager) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(manager); Services = services; PartManager = manager; diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreBuilder.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreBuilder.cs index 088ae7ce1443..05962f8162a1 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreBuilder.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreBuilder.cs @@ -19,15 +19,8 @@ public MvcCoreBuilder( IServiceCollection services, ApplicationPartManager manager) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(manager); Services = services; PartManager = manager; diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcBuilderExtensions.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcBuilderExtensions.cs index 09be76d9129c..c8f4e72cef28 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcBuilderExtensions.cs @@ -27,15 +27,8 @@ public static IMvcBuilder AddMvcOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -52,15 +45,8 @@ public static IMvcBuilder AddJsonOptions( this IMvcBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure(configure); return builder; @@ -76,15 +62,8 @@ public static IMvcBuilder AddFormatterMappings( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure((options) => setupAction(options.FormatterMappings)); return builder; @@ -99,15 +78,8 @@ public static IMvcBuilder AddFormatterMappings( /// The . public static IMvcBuilder AddApplicationPart(this IMvcBuilder builder, Assembly assembly) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(assembly); builder.ConfigureApplicationPartManager(manager => { @@ -132,15 +104,8 @@ public static IMvcBuilder ConfigureApplicationPartManager( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); setupAction(builder.PartManager); @@ -154,10 +119,7 @@ public static IMvcBuilder ConfigureApplicationPartManager( /// The . public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); var feature = new ControllerFeature(); builder.PartManager.PopulateFeature(feature); @@ -183,10 +145,7 @@ public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder) UrlFormat = "https://aka.ms/aspnetcore-warnings/{0}")] public static IMvcBuilder SetCompatibilityVersion(this IMvcBuilder builder, CompatibilityVersion version) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(o => o.CompatibilityVersion = version); return builder; @@ -202,15 +161,8 @@ public static IMvcBuilder ConfigureApiBehaviorOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcCoreBuilderExtensions.cs index 15a9e2478498..10bdc9e6acd0 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreMvcCoreBuilderExtensions.cs @@ -29,15 +29,8 @@ public static IMvcCoreBuilder AddMvcOptions( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -53,15 +46,8 @@ public static IMvcCoreBuilder AddJsonOptions( this IMvcCoreBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure(configure); return builder; @@ -174,15 +160,8 @@ public static IMvcCoreBuilder AddControllersAsServices(this IMvcCoreBuilder buil /// The . public static IMvcCoreBuilder AddApplicationPart(this IMvcCoreBuilder builder, Assembly assembly) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(assembly); builder.ConfigureApplicationPartManager(manager => { @@ -207,15 +186,8 @@ public static IMvcCoreBuilder ConfigureApplicationPartManager( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); setupAction(builder.PartManager); @@ -232,15 +204,8 @@ public static IMvcCoreBuilder ConfigureApiBehaviorOptions( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); @@ -258,10 +223,7 @@ public static IMvcCoreBuilder ConfigureApiBehaviorOptions( UrlFormat = "https://aka.ms/aspnetcore-warnings/{0}")] public static IMvcCoreBuilder SetCompatibilityVersion(this IMvcCoreBuilder builder, CompatibilityVersion version) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(o => o.CompatibilityVersion = version); return builder; diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreRouteOptionsSetup.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreRouteOptionsSetup.cs index 078c69bdb5f2..31adb9ca316c 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreRouteOptionsSetup.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreRouteOptionsSetup.cs @@ -18,10 +18,7 @@ internal sealed class MvcCoreRouteOptionsSetup : IConfigureOptions /// The . public void Configure(RouteOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.ConstraintMap.Add("exists", typeof(KnownRouteValueConstraint)); } diff --git a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs index f81bd4df0bb3..a8178f76ca78 100644 --- a/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs +++ b/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs @@ -46,10 +46,7 @@ public static class MvcCoreServiceCollectionExtensions /// public static IMvcCoreBuilder AddMvcCore(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var environment = GetServiceFromCollection(services); var partManager = GetApplicationPartManager(services, environment); @@ -119,15 +116,8 @@ public static IMvcCoreBuilder AddMvcCore( this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); var builder = services.AddMvcCore(); services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Core/src/FileContentResult.cs b/src/Mvc/Mvc.Core/src/FileContentResult.cs index 896df2ab04ac..2c5c0b736985 100644 --- a/src/Mvc/Mvc.Core/src/FileContentResult.cs +++ b/src/Mvc/Mvc.Core/src/FileContentResult.cs @@ -38,10 +38,7 @@ public FileContentResult(byte[] fileContents, string contentType) public FileContentResult(byte[] fileContents, MediaTypeHeaderValue contentType) : base(contentType.ToString()) { - if (fileContents == null) - { - throw new ArgumentNullException(nameof(fileContents)); - } + ArgumentNullException.ThrowIfNull(fileContents); FileContents = fileContents; } @@ -55,10 +52,7 @@ public byte[] FileContents [MemberNotNull(nameof(_fileContents))] set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _fileContents = value; } @@ -67,10 +61,7 @@ public byte[] FileContents /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/FileResult.cs b/src/Mvc/Mvc.Core/src/FileResult.cs index 3ef9f8001690..cf946444d3c4 100644 --- a/src/Mvc/Mvc.Core/src/FileResult.cs +++ b/src/Mvc/Mvc.Core/src/FileResult.cs @@ -21,10 +21,7 @@ public abstract class FileResult : ActionResult /// The Content-Type header of the response. protected FileResult(string contentType) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); ContentType = contentType; } diff --git a/src/Mvc/Mvc.Core/src/FileStreamResult.cs b/src/Mvc/Mvc.Core/src/FileStreamResult.cs index f3e373110650..239bb73e6024 100644 --- a/src/Mvc/Mvc.Core/src/FileStreamResult.cs +++ b/src/Mvc/Mvc.Core/src/FileStreamResult.cs @@ -38,10 +38,7 @@ public FileStreamResult(Stream fileStream, string contentType) public FileStreamResult(Stream fileStream, MediaTypeHeaderValue contentType) : base(contentType.ToString()) { - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream)); - } + ArgumentNullException.ThrowIfNull(fileStream); FileStream = fileStream; } @@ -56,10 +53,7 @@ public Stream FileStream [MemberNotNull(nameof(_fileStream))] set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _fileStream = value; } @@ -68,10 +62,7 @@ public Stream FileStream /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/Filters/ActionFilterAttribute.cs b/src/Mvc/Mvc.Core/src/Filters/ActionFilterAttribute.cs index 87599faeb81d..55a67f12b1b6 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ActionFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ActionFilterAttribute.cs @@ -32,15 +32,8 @@ public virtual async Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); OnActionExecuting(context); if (context.Result == null) @@ -64,15 +57,8 @@ public virtual async Task OnResultExecutionAsync( ResultExecutingContext context, ResultExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); OnResultExecuting(context); if (!context.Cancel) diff --git a/src/Mvc/Mvc.Core/src/Filters/ControllerActionFilter.cs b/src/Mvc/Mvc.Core/src/Filters/ControllerActionFilter.cs index a9ff34679615..36212e091b43 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ControllerActionFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ControllerActionFilter.cs @@ -19,15 +19,8 @@ public Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); var controller = context.Controller; if (controller == null) diff --git a/src/Mvc/Mvc.Core/src/Filters/ControllerResultFilter.cs b/src/Mvc/Mvc.Core/src/Filters/ControllerResultFilter.cs index 9a39762f9669..4111d76dfd59 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ControllerResultFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ControllerResultFilter.cs @@ -19,15 +19,8 @@ public Task OnResultExecutionAsync( ResultExecutingContext context, ResultExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); var controller = context.Controller; if (controller == null) diff --git a/src/Mvc/Mvc.Core/src/Filters/DefaultFilterProvider.cs b/src/Mvc/Mvc.Core/src/Filters/DefaultFilterProvider.cs index d9e31adbf1d6..0b1e3c1d4bfd 100644 --- a/src/Mvc/Mvc.Core/src/Filters/DefaultFilterProvider.cs +++ b/src/Mvc/Mvc.Core/src/Filters/DefaultFilterProvider.cs @@ -13,10 +13,7 @@ internal sealed class DefaultFilterProvider : IFilterProvider /// public void OnProvidersExecuting(FilterProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ActionContext.ActionDescriptor.FilterDescriptors != null) { diff --git a/src/Mvc/Mvc.Core/src/Filters/DisableRequestSizeLimitFilter.cs b/src/Mvc/Mvc.Core/src/Filters/DisableRequestSizeLimitFilter.cs index 9a8c21f6316c..f20fa596c810 100644 --- a/src/Mvc/Mvc.Core/src/Filters/DisableRequestSizeLimitFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/DisableRequestSizeLimitFilter.cs @@ -31,10 +31,7 @@ public DisableRequestSizeLimitFilter(ILoggerFactory loggerFactory) /// the is not applied. public void OnAuthorization(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var effectivePolicy = context.FindEffectivePolicy(); if (effectivePolicy != null && effectivePolicy != this) diff --git a/src/Mvc/Mvc.Core/src/Filters/ExceptionFilterAttribute.cs b/src/Mvc/Mvc.Core/src/Filters/ExceptionFilterAttribute.cs index c1fa91795f34..f79fb39205a4 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ExceptionFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ExceptionFilterAttribute.cs @@ -16,10 +16,7 @@ public abstract class ExceptionFilterAttribute : Attribute, IAsyncExceptionFilte /// public virtual Task OnExceptionAsync(ExceptionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); OnException(context); return Task.CompletedTask; diff --git a/src/Mvc/Mvc.Core/src/Filters/FilterCollection.cs b/src/Mvc/Mvc.Core/src/Filters/FilterCollection.cs index 05996a02fbe4..2054291759d1 100644 --- a/src/Mvc/Mvc.Core/src/Filters/FilterCollection.cs +++ b/src/Mvc/Mvc.Core/src/Filters/FilterCollection.cs @@ -40,10 +40,7 @@ public IFilterMetadata Add() where TFilterType : IFilterMetadata /// public IFilterMetadata Add(Type filterType) { - if (filterType == null) - { - throw new ArgumentNullException(nameof(filterType)); - } + ArgumentNullException.ThrowIfNull(filterType); return Add(filterType, order: 0); } @@ -77,10 +74,7 @@ public IFilterMetadata Add(int order) where TFilterType : IFilterMe /// public IFilterMetadata Add(Type filterType, int order) { - if (filterType == null) - { - throw new ArgumentNullException(nameof(filterType)); - } + ArgumentNullException.ThrowIfNull(filterType); if (!typeof(IFilterMetadata).IsAssignableFrom(filterType)) { @@ -124,10 +118,7 @@ public IFilterMetadata AddService() where TFilterType : IFilterMeta /// public IFilterMetadata AddService(Type filterType) { - if (filterType == null) - { - throw new ArgumentNullException(nameof(filterType)); - } + ArgumentNullException.ThrowIfNull(filterType); return AddService(filterType, order: 0); } @@ -161,10 +152,7 @@ public IFilterMetadata AddService(int order) where TFilterType : IF /// public IFilterMetadata AddService(Type filterType, int order) { - if (filterType == null) - { - throw new ArgumentNullException(nameof(filterType)); - } + ArgumentNullException.ThrowIfNull(filterType); if (!typeof(IFilterMetadata).IsAssignableFrom(filterType)) { diff --git a/src/Mvc/Mvc.Core/src/Filters/FilterDescriptorOrderComparer.cs b/src/Mvc/Mvc.Core/src/Filters/FilterDescriptorOrderComparer.cs index 39d35a510e4d..3d95b3ee1b36 100644 --- a/src/Mvc/Mvc.Core/src/Filters/FilterDescriptorOrderComparer.cs +++ b/src/Mvc/Mvc.Core/src/Filters/FilterDescriptorOrderComparer.cs @@ -9,15 +9,8 @@ internal sealed class FilterDescriptorOrderComparer : IComparerA type which configures a middleware pipeline. public MiddlewareFilterAttribute(Type configurationType) { - if (configurationType == null) - { - throw new ArgumentNullException(nameof(configurationType)); - } + ArgumentNullException.ThrowIfNull(configurationType); ConfigurationType = configurationType; } @@ -41,10 +38,7 @@ public MiddlewareFilterAttribute(Type configurationType) /// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); var middlewarePipelineService = serviceProvider.GetRequiredService(); var pipeline = middlewarePipelineService.GetPipeline(ConfigurationType); diff --git a/src/Mvc/Mvc.Core/src/Filters/MiddlewareFilterConfigurationProvider.cs b/src/Mvc/Mvc.Core/src/Filters/MiddlewareFilterConfigurationProvider.cs index e17ecbc0afdd..42b38e2cc5fd 100644 --- a/src/Mvc/Mvc.Core/src/Filters/MiddlewareFilterConfigurationProvider.cs +++ b/src/Mvc/Mvc.Core/src/Filters/MiddlewareFilterConfigurationProvider.cs @@ -17,10 +17,7 @@ internal sealed class MiddlewareFilterConfigurationProvider { public static Action CreateConfigureDelegate(Type configurationType) { - if (configurationType == null) - { - throw new ArgumentNullException(nameof(configurationType)); - } + ArgumentNullException.ThrowIfNull(configurationType); if (!HasParameterlessConstructor(configurationType)) { diff --git a/src/Mvc/Mvc.Core/src/Filters/RequestFormLimitsFilter.cs b/src/Mvc/Mvc.Core/src/Filters/RequestFormLimitsFilter.cs index 5cc245688be0..44f54407048b 100644 --- a/src/Mvc/Mvc.Core/src/Filters/RequestFormLimitsFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/RequestFormLimitsFilter.cs @@ -22,10 +22,7 @@ public RequestFormLimitsFilter(ILoggerFactory loggerFactory) public void OnAuthorization(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var effectivePolicy = context.FindEffectivePolicy(); if (effectivePolicy != null && effectivePolicy != this) diff --git a/src/Mvc/Mvc.Core/src/Filters/RequestSizeLimitFilter.cs b/src/Mvc/Mvc.Core/src/Filters/RequestSizeLimitFilter.cs index 06c441d6363f..cda3ef2778ee 100644 --- a/src/Mvc/Mvc.Core/src/Filters/RequestSizeLimitFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/RequestSizeLimitFilter.cs @@ -33,10 +33,7 @@ public RequestSizeLimitFilter(ILoggerFactory loggerFactory) /// the is not applied. public void OnAuthorization(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var effectivePolicy = context.FindEffectivePolicy(); if (effectivePolicy != null && effectivePolicy != this) diff --git a/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilter.cs b/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilter.cs index b60d10d9e1db..143302f1651d 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilter.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilter.cs @@ -81,10 +81,7 @@ public string[]? VaryByQueryKeys /// public void OnActionExecuting(ActionExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // If there are more filters which can override the values written by this filter, // then skip execution of this filter. diff --git a/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilterExecutor.cs b/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilterExecutor.cs index a46755969db7..aa5155778ec8 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilterExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ResponseCacheFilterExecutor.cs @@ -54,10 +54,7 @@ public string[]? VaryByQueryKeys public void Execute(FilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!NoStore) { diff --git a/src/Mvc/Mvc.Core/src/Filters/ResultFilterAttribute.cs b/src/Mvc/Mvc.Core/src/Filters/ResultFilterAttribute.cs index 9a2b6d5d9e64..30a28449932b 100644 --- a/src/Mvc/Mvc.Core/src/Filters/ResultFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/Filters/ResultFilterAttribute.cs @@ -29,15 +29,8 @@ public virtual async Task OnResultExecutionAsync( ResultExecutingContext context, ResultExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); OnResultExecuting(context); if (!context.Cancel) diff --git a/src/Mvc/Mvc.Core/src/ForbidResult.cs b/src/Mvc/Mvc.Core/src/ForbidResult.cs index ae99bdac04e3..d7e33955a93e 100644 --- a/src/Mvc/Mvc.Core/src/ForbidResult.cs +++ b/src/Mvc/Mvc.Core/src/ForbidResult.cs @@ -90,10 +90,7 @@ public ForbidResult(IList authenticationSchemes, AuthenticationPropertie /// public override async Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var httpContext = context.HttpContext; diff --git a/src/Mvc/Mvc.Core/src/FormatFilterAttribute.cs b/src/Mvc/Mvc.Core/src/FormatFilterAttribute.cs index 316bdd3d14ca..1346a22ebc73 100644 --- a/src/Mvc/Mvc.Core/src/FormatFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/FormatFilterAttribute.cs @@ -24,10 +24,7 @@ public class FormatFilterAttribute : Attribute, IFilterFactory /// An instance of . public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); return serviceProvider.GetRequiredService(); } diff --git a/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs b/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs index 3dc934705166..3e85d97a89ad 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs @@ -18,15 +18,8 @@ public static IList ParseAcceptHeader(IList public static void ParseAcceptHeader(IList acceptHeaders, IList parsedValues) { - if (acceptHeaders == null) - { - throw new ArgumentNullException(nameof(acceptHeaders)); - } - - if (parsedValues == null) - { - throw new ArgumentNullException(nameof(parsedValues)); - } + ArgumentNullException.ThrowIfNull(acceptHeaders); + ArgumentNullException.ThrowIfNull(parsedValues); for (var i = 0; i < acceptHeaders.Count; i++) { var charIndex = 0; diff --git a/src/Mvc/Mvc.Core/src/Formatters/FormatFilter.cs b/src/Mvc/Mvc.Core/src/Formatters/FormatFilter.cs index 83d80a6cd2b3..518846fe48fa 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/FormatFilter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/FormatFilter.cs @@ -26,15 +26,8 @@ public partial class FormatFilter : IFormatFilter, IResourceFilter, IResultFilte /// The . public FormatFilter(IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _options = options.Value; _logger = loggerFactory.CreateLogger(GetType()); @@ -67,10 +60,7 @@ public FormatFilter(IOptions options, ILoggerFactory loggerFactory) /// The . public void OnResourceExecuting(ResourceExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var format = GetFormat(context); if (format == null) @@ -141,10 +131,7 @@ public void OnResourceExecuted(ResourceExecutedContext context) /// The . public void OnResultExecuting(ResultExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var format = GetFormat(context); if (format == null) diff --git a/src/Mvc/Mvc.Core/src/Formatters/FormatterMappings.cs b/src/Mvc/Mvc.Core/src/Formatters/FormatterMappings.cs index c06d357704ce..24e11e88a3a5 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/FormatterMappings.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/FormatterMappings.cs @@ -23,15 +23,8 @@ public class FormatterMappings /// The media type for the format value. public void SetMediaTypeMappingForFormat(string format, string contentType) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(contentType); SetMediaTypeMappingForFormat(format, MediaTypeHeaderValue.Parse(contentType)); } @@ -44,15 +37,8 @@ public void SetMediaTypeMappingForFormat(string format, string contentType) /// The media type for the format value. public void SetMediaTypeMappingForFormat(string format, MediaTypeHeaderValue contentType) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(contentType); ValidateContentType(contentType); format = RemovePeriodIfPresent(format); @@ -88,10 +74,7 @@ public void SetMediaTypeMappingForFormat(string format, MediaTypeHeaderValue con /// true if the format is successfully found and cleared; otherwise, false. public bool ClearMediaTypeMappingForFormat(string format) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } + ArgumentNullException.ThrowIfNull(format); format = RemovePeriodIfPresent(format); return _map.Remove(format); diff --git a/src/Mvc/Mvc.Core/src/Formatters/InputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/InputFormatter.cs index 0edead1188b2..2474e63ab177 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/InputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/InputFormatter.cs @@ -25,10 +25,7 @@ public abstract class InputFormatter : IInputFormatter, IApiRequestFormatMetadat /// The default value for the type. protected virtual object? GetDefaultValueForType(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); if (modelType.IsValueType) { @@ -94,10 +91,7 @@ protected virtual bool CanReadType(Type type) /// public virtual Task ReadAsync(InputFormatterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var canHaveBody = context.HttpContext.Features.Get()?.CanHaveBody; // In case the feature is not registered diff --git a/src/Mvc/Mvc.Core/src/Formatters/MediaType.cs b/src/Mvc/Mvc.Core/src/Formatters/MediaType.cs index da49be5db31c..8fdb1596b086 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/MediaType.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/MediaType.cs @@ -44,10 +44,7 @@ public MediaType(StringSegment mediaType) /// The length of the media type to parse if provided. public MediaType(string mediaType, int offset, int? length) { - if (mediaType == null) - { - throw new ArgumentNullException(nameof(mediaType)); - } + ArgumentNullException.ThrowIfNull(mediaType); if (offset < 0 || offset >= mediaType.Length) { diff --git a/src/Mvc/Mvc.Core/src/Formatters/MediaTypeCollection.cs b/src/Mvc/Mvc.Core/src/Formatters/MediaTypeCollection.cs index e1dc5ebc316e..f545768816a8 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/MediaTypeCollection.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/MediaTypeCollection.cs @@ -17,10 +17,7 @@ public class MediaTypeCollection : Collection /// The media type to be added to the end of the . public void Add(MediaTypeHeaderValue item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); Add(item.ToString()); } @@ -37,10 +34,7 @@ public void Insert(int index, MediaTypeHeaderValue item) throw new ArgumentOutOfRangeException(nameof(index)); } - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); Insert(index, item.ToString()); } @@ -54,10 +48,7 @@ public void Insert(int index, MediaTypeHeaderValue item) /// . public bool Remove(MediaTypeHeaderValue item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return Remove(item.ToString()); } diff --git a/src/Mvc/Mvc.Core/src/Formatters/OutputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/OutputFormatter.cs index 7c791ee177b5..362171af2b8c 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/OutputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/OutputFormatter.cs @@ -92,10 +92,7 @@ protected virtual bool CanWriteType(Type? type) /// public virtual bool CanWriteResult(OutputFormatterCanWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (SupportedMediaTypes.Count == 0) { @@ -159,10 +156,7 @@ public virtual bool CanWriteResult(OutputFormatterCanWriteContext context) /// public virtual Task WriteAsync(OutputFormatterWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); WriteResponseHeaders(context); return WriteResponseBodyAsync(context); @@ -174,10 +168,7 @@ public virtual Task WriteAsync(OutputFormatterWriteContext context) /// The formatter context associated with the call. public virtual void WriteResponseHeaders(OutputFormatterWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var response = context.HttpContext.Response; response.ContentType = context.ContentType.Value ?? string.Empty; diff --git a/src/Mvc/Mvc.Core/src/Formatters/StreamOutputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/StreamOutputFormatter.cs index b25ca6e953db..6185c6c2c60c 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/StreamOutputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/StreamOutputFormatter.cs @@ -12,10 +12,7 @@ public class StreamOutputFormatter : IOutputFormatter /// public bool CanWriteResult(OutputFormatterCanWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Ignore the passed in content type, if the object is a Stream. if (context.Object is Stream) @@ -29,10 +26,7 @@ public bool CanWriteResult(OutputFormatterCanWriteContext context) /// public async Task WriteAsync(OutputFormatterWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); using (var valueAsStream = ((Stream)context.Object!)) { diff --git a/src/Mvc/Mvc.Core/src/Formatters/StringOutputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/StringOutputFormatter.cs index 1eabf3da0c8d..1fa91387f90e 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/StringOutputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/StringOutputFormatter.cs @@ -28,10 +28,7 @@ public StringOutputFormatter() /// public override bool CanWriteResult(OutputFormatterCanWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ObjectType == typeof(string) || context.Object is string) { @@ -45,15 +42,8 @@ public override bool CanWriteResult(OutputFormatterCanWriteContext context) /// public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var valueAsString = (string?)context.Object; if (string.IsNullOrEmpty(valueAsString)) diff --git a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs index 02a4e23b283a..dd2285518075 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonInputFormatter.cs @@ -54,15 +54,8 @@ public sealed override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var httpContext = context.HttpContext; var (inputStream, usesTranscodingStream) = GetInputStream(httpContext, encoding); diff --git a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs index 54e14704e7e9..ba1e404a1d96 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs @@ -56,15 +56,8 @@ internal static SystemTextJsonOutputFormatter CreateFormatter(JsonOptions jsonOp /// public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (selectedEncoding == null) - { - throw new ArgumentNullException(nameof(selectedEncoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(selectedEncoding); var httpContext = context.HttpContext; diff --git a/src/Mvc/Mvc.Core/src/Formatters/TextInputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/TextInputFormatter.cs index 427c711f177f..c8ac81d79158 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/TextInputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/TextInputFormatter.cs @@ -34,10 +34,7 @@ protected static readonly Encoding UTF16EncodingLittleEndian /// public override Task ReadRequestBodyAsync(InputFormatterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var selectedEncoding = SelectCharacterEncoding(context); if (selectedEncoding == null) @@ -75,10 +72,7 @@ public abstract Task ReadRequestBodyAsync( /// protected Encoding? SelectCharacterEncoding(InputFormatterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (SupportedEncodings.Count == 0) { diff --git a/src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs b/src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs index 2d231ab7585b..10ec7bf26fed 100644 --- a/src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs +++ b/src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs @@ -62,10 +62,7 @@ private IDictionary OutputMediaTypeCache /// The to use when reading the request or writing the response. public virtual Encoding SelectCharacterEncoding(OutputFormatterWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (SupportedEncodings.Count == 0) { @@ -105,10 +102,7 @@ public virtual Encoding SelectCharacterEncoding(OutputFormatterWriteContext cont /// public override Task WriteAsync(OutputFormatterWriteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var selectedMediaType = context.ContentType; if (!selectedMediaType.HasValue) diff --git a/src/Mvc/Mvc.Core/src/HttpDeleteAttribute.cs b/src/Mvc/Mvc.Core/src/HttpDeleteAttribute.cs index fabac03baf2a..6eac4d9fc21a 100644 --- a/src/Mvc/Mvc.Core/src/HttpDeleteAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpDeleteAttribute.cs @@ -28,9 +28,6 @@ public HttpDeleteAttribute() public HttpDeleteAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpGetAttribute.cs b/src/Mvc/Mvc.Core/src/HttpGetAttribute.cs index 95e860c74201..2995c09d0b6d 100644 --- a/src/Mvc/Mvc.Core/src/HttpGetAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpGetAttribute.cs @@ -28,9 +28,6 @@ public HttpGetAttribute() public HttpGetAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpHeadAttribute.cs b/src/Mvc/Mvc.Core/src/HttpHeadAttribute.cs index 63be84cc0a75..ed4c12c57d32 100644 --- a/src/Mvc/Mvc.Core/src/HttpHeadAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpHeadAttribute.cs @@ -28,9 +28,6 @@ public HttpHeadAttribute() public HttpHeadAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpOptionsAttribute.cs b/src/Mvc/Mvc.Core/src/HttpOptionsAttribute.cs index 347ea1d1e081..ced447f39be9 100644 --- a/src/Mvc/Mvc.Core/src/HttpOptionsAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpOptionsAttribute.cs @@ -28,9 +28,6 @@ public HttpOptionsAttribute() public HttpOptionsAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpPatchAttribute.cs b/src/Mvc/Mvc.Core/src/HttpPatchAttribute.cs index 4d59e23337b2..a88aa11a2db7 100644 --- a/src/Mvc/Mvc.Core/src/HttpPatchAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpPatchAttribute.cs @@ -28,9 +28,6 @@ public HttpPatchAttribute() public HttpPatchAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpPostAttribute.cs b/src/Mvc/Mvc.Core/src/HttpPostAttribute.cs index 39a184ee8b57..e64a73e4c31c 100644 --- a/src/Mvc/Mvc.Core/src/HttpPostAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpPostAttribute.cs @@ -28,9 +28,6 @@ public HttpPostAttribute() public HttpPostAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/HttpPutAttribute.cs b/src/Mvc/Mvc.Core/src/HttpPutAttribute.cs index e09694f6289b..deb4d79f10a7 100644 --- a/src/Mvc/Mvc.Core/src/HttpPutAttribute.cs +++ b/src/Mvc/Mvc.Core/src/HttpPutAttribute.cs @@ -28,9 +28,6 @@ public HttpPutAttribute() public HttpPutAttribute([StringSyntax("Route")] string template) : base(_supportedMethods, template) { - if (template == null) - { - throw new ArgumentNullException(nameof(template)); - } + ArgumentNullException.ThrowIfNull(template); } } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ActionDescriptorCollection.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ActionDescriptorCollection.cs index 0d3ddcbf2d26..a82b2dc72899 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ActionDescriptorCollection.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ActionDescriptorCollection.cs @@ -19,10 +19,7 @@ public class ActionDescriptorCollection /// The unique version of discovered actions. public ActionDescriptorCollection(IReadOnlyList items, int version) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); Items = items; Version = version; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ActionResultTypeMapper.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ActionResultTypeMapper.cs index 2727fd6e1e5e..beb6e015c2c6 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ActionResultTypeMapper.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ActionResultTypeMapper.cs @@ -11,10 +11,7 @@ internal sealed class ActionResultTypeMapper : IActionResultTypeMapper { public Type GetResultDataType(Type returnType) { - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(ActionResult<>)) @@ -27,10 +24,7 @@ public Type GetResultDataType(Type returnType) public IActionResult Convert(object? value, Type returnType) { - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } + ArgumentNullException.ThrowIfNull(returnType); if (value is IConvertToActionResult converter) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ActionSelector.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ActionSelector.cs index 8526c3a572a0..2c1feaf3e8c7 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ActionSelector.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ActionSelector.cs @@ -62,10 +62,7 @@ private ActionSelectionTable Current public IReadOnlyList SelectCandidates(RouteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var cache = Current; @@ -81,15 +78,8 @@ public IReadOnlyList SelectCandidates(RouteContext context) public ActionDescriptor? SelectBestCandidate(RouteContext context, IReadOnlyList candidates) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(candidates); var finalMatches = EvaluateActionConstraints(context, candidates); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ClientErrorResultFilter.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ClientErrorResultFilter.cs index 07328df79414..474624716c51 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ClientErrorResultFilter.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ClientErrorResultFilter.cs @@ -31,10 +31,7 @@ public void OnResultExecuted(ResultExecutedContext context) public void OnResultExecuting(ResultExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!(context.Result is IClientErrorActionResult clientError)) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/CompatibilitySwitch.cs b/src/Mvc/Mvc.Core/src/Infrastructure/CompatibilitySwitch.cs index 911d8cd5c6b0..93fe44a30123 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/CompatibilitySwitch.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/CompatibilitySwitch.cs @@ -77,10 +77,7 @@ public CompatibilitySwitch(string name) /// public CompatibilitySwitch(string name, TValue initialValue) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; _value = initialValue; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ConfigureCompatibilityOptions.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ConfigureCompatibilityOptions.cs index 9802f27d8e1e..26d50c08640e 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ConfigureCompatibilityOptions.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ConfigureCompatibilityOptions.cs @@ -29,10 +29,7 @@ protected ConfigureCompatibilityOptions( ILoggerFactory loggerFactory, IOptions compatibilityOptions) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); Version = compatibilityOptions.Value.CompatibilityVersion; _logger = loggerFactory.CreateLogger(); @@ -52,15 +49,8 @@ protected ConfigureCompatibilityOptions( /// public virtual void PostConfigure(string? name, TOptions options) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(options); // Evaluate DefaultValues once so subclasses don't have to cache. var defaultValues = DefaultValues; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ContentResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ContentResultExecutor.cs index 5529cd232eb6..f6226de5979b 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ContentResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ContentResultExecutor.cs @@ -33,15 +33,8 @@ public ContentResultExecutor(ILogger logger, IHttpRespons /// public virtual async Task ExecuteAsync(ActionContext context, ContentResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var response = context.HttpContext.Response; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs index 4341070894c2..8aef2b4dd2e6 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvoker.cs @@ -37,10 +37,7 @@ internal ControllerActionInvoker( IFilterMetadata[] filters) : base(diagnosticListener, logger, actionContextAccessor, mapper, controllerContext, filters, controllerContext.ValueProviderFactories) { - if (cacheEntry == null) - { - throw new ArgumentNullException(nameof(cacheEntry)); - } + ArgumentNullException.ThrowIfNull(cacheEntry); _cacheEntry = cacheEntry; _controllerContext = controllerContext; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvokerProvider.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvokerProvider.cs index e3f03f88aa29..432fa8565373 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvokerProvider.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ControllerActionInvokerProvider.cs @@ -59,10 +59,7 @@ public ControllerActionInvokerProvider( /// public void OnProvidersExecuting(ActionInvokerProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.ActionContext.ActionDescriptor is ControllerActionDescriptor) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/DefaultOutputFormatterSelector.cs b/src/Mvc/Mvc.Core/src/Infrastructure/DefaultOutputFormatterSelector.cs index 7a5657ddf1c0..7e427c07f45a 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/DefaultOutputFormatterSelector.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/DefaultOutputFormatterSelector.cs @@ -36,15 +36,8 @@ public partial class DefaultOutputFormatterSelector : OutputFormatterSelector /// The logger factory. public DefaultOutputFormatterSelector(IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); @@ -56,20 +49,9 @@ public DefaultOutputFormatterSelector(IOptions options, ILoggerFacto /// public override IOutputFormatter? SelectFormatter(OutputFormatterCanWriteContext context, IList formatters, MediaTypeCollection contentTypes) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (formatters == null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (contentTypes == null) - { - throw new ArgumentNullException(nameof(contentTypes)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(formatters); + ArgumentNullException.ThrowIfNull(contentTypes); ValidateContentTypes(contentTypes); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs b/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs index c08e86de6b9f..0d226c00c768 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/DefaultProblemDetailsFactory.cs @@ -56,10 +56,7 @@ public override ValidationProblemDetails CreateValidationProblemDetails( string? detail = null, string? instance = null) { - if (modelStateDictionary == null) - { - throw new ArgumentNullException(nameof(modelStateDictionary)); - } + ArgumentNullException.ThrowIfNull(modelStateDictionary); statusCode ??= 400; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/FileContentResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/FileContentResultExecutor.cs index 734f9b5db03b..8f380ea3009d 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/FileContentResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/FileContentResultExecutor.cs @@ -25,15 +25,8 @@ public FileContentResultExecutor(ILoggerFactory loggerFactory) /// public virtual Task ExecuteAsync(ActionContext context, FileContentResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); Log.ExecutingFileResult(Logger, result); @@ -62,15 +55,8 @@ public virtual Task ExecuteAsync(ActionContext context, FileContentResult result /// The length of the range. protected virtual Task WriteFileAsync(ActionContext context, FileContentResult result, RangeItemHeaderValue? range, long rangeLength) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); if (range != null && rangeLength == 0) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs b/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs index 44ac1e06830a..9881209a2779 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/FileResultExecutorBase.cs @@ -78,10 +78,7 @@ protected virtual (RangeItemHeaderValue? range, long rangeLength, bool serveBody /// An . protected static ILogger CreateLogger(ILoggerFactory factory) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(factory); return factory.CreateLogger(); } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/FileStreamResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/FileStreamResultExecutor.cs index 8341dca9e367..a2c4f017a3c4 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/FileStreamResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/FileStreamResultExecutor.cs @@ -25,15 +25,8 @@ public FileStreamResultExecutor(ILoggerFactory loggerFactory) /// public virtual async Task ExecuteAsync(ActionContext context, FileStreamResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); using (result.FileStream) { @@ -75,15 +68,8 @@ protected virtual Task WriteFileAsync( RangeItemHeaderValue? range, long rangeLength) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); if (range != null && rangeLength == 0) { diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/LocalRedirectResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/LocalRedirectResultExecutor.cs index 51d386c6ef5f..bd5ef6e699fe 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/LocalRedirectResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/LocalRedirectResultExecutor.cs @@ -25,15 +25,8 @@ public partial class LocalRedirectResultExecutor : IActionResultExecutorUsed to create url helpers. public LocalRedirectResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory urlHelperFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(urlHelperFactory); _logger = loggerFactory.CreateLogger(); _urlHelperFactory = urlHelperFactory; @@ -42,15 +35,8 @@ public LocalRedirectResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFacto /// public virtual Task ExecuteAsync(ActionContext context, LocalRedirectResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs index 9c33798e14ed..c95ec0f7ad97 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpRequestStreamReaderFactory.cs @@ -35,15 +35,8 @@ public MemoryPoolHttpRequestStreamReaderFactory( ArrayPool bytePool, ArrayPool charPool) { - if (bytePool == null) - { - throw new ArgumentNullException(nameof(bytePool)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } + ArgumentNullException.ThrowIfNull(bytePool); + ArgumentNullException.ThrowIfNull(charPool); _bytePool = bytePool; _charPool = charPool; @@ -52,15 +45,8 @@ public MemoryPoolHttpRequestStreamReaderFactory( /// public TextReader CreateReader(Stream stream, Encoding encoding) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(encoding); return new HttpRequestStreamReader(stream, encoding, DefaultBufferSize, _bytePool, _charPool); } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs index 111970dbcd47..23904b68dddf 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/MemoryPoolHttpResponseStreamWriterFactory.cs @@ -43,15 +43,8 @@ public MemoryPoolHttpResponseStreamWriterFactory( ArrayPool bytePool, ArrayPool charPool) { - if (bytePool == null) - { - throw new ArgumentNullException(nameof(bytePool)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } + ArgumentNullException.ThrowIfNull(bytePool); + ArgumentNullException.ThrowIfNull(charPool); _bytePool = bytePool; _charPool = charPool; @@ -60,15 +53,8 @@ public MemoryPoolHttpResponseStreamWriterFactory( /// public TextWriter CreateWriter(Stream stream, Encoding encoding) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(encoding); return new HttpResponseStreamWriter(stream, encoding, DefaultBufferSize, _bytePool, _charPool); } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/MvcCoreMvcOptionsSetup.cs b/src/Mvc/Mvc.Core/src/Infrastructure/MvcCoreMvcOptionsSetup.cs index 5ae0d2c9105e..7f72ccd8ed62 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/MvcCoreMvcOptionsSetup.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/MvcCoreMvcOptionsSetup.cs @@ -33,20 +33,9 @@ public MvcCoreMvcOptionsSetup(IHttpRequestStreamReaderFactory readerFactory) public MvcCoreMvcOptionsSetup(IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory loggerFactory, IOptions jsonOptions) { - if (readerFactory == null) - { - throw new ArgumentNullException(nameof(readerFactory)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (jsonOptions == null) - { - throw new ArgumentNullException(nameof(jsonOptions)); - } + ArgumentNullException.ThrowIfNull(readerFactory); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(jsonOptions); _readerFactory = readerFactory; _loggerFactory = loggerFactory; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/NonDisposableStream.cs b/src/Mvc/Mvc.Core/src/Infrastructure/NonDisposableStream.cs index 4c6db17889f0..063199499c72 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/NonDisposableStream.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/NonDisposableStream.cs @@ -20,10 +20,7 @@ internal sealed class NonDisposableStream : Stream /// The stream which should not be closed or flushed. public NonDisposableStream(Stream innerStream) { - if (innerStream == null) - { - throw new ArgumentNullException(nameof(innerStream)); - } + ArgumentNullException.ThrowIfNull(innerStream); _innerStream = innerStream; } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs index d8bab1ab8ef6..1bca41a29da4 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs @@ -30,20 +30,9 @@ public ObjectResultExecutor( ILoggerFactory loggerFactory, IOptions mvcOptions) { - if (formatterSelector == null) - { - throw new ArgumentNullException(nameof(formatterSelector)); - } - - if (writerFactory == null) - { - throw new ArgumentNullException(nameof(writerFactory)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(formatterSelector); + ArgumentNullException.ThrowIfNull(writerFactory); + ArgumentNullException.ThrowIfNull(loggerFactory); FormatterSelector = formatterSelector; WriterFactory = writerFactory.CreateWriter; @@ -75,15 +64,8 @@ public ObjectResultExecutor( /// public virtual Task ExecuteAsync(ActionContext context, ObjectResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); InferContentTypes(context, result); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ParameterDefaultValues.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ParameterDefaultValues.cs index 0aecf41a0f4d..471aa4339850 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ParameterDefaultValues.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ParameterDefaultValues.cs @@ -11,10 +11,7 @@ internal static class ParameterDefaultValues { public static object?[] GetParameterDefaultValues(MethodBase methodInfo) { - if (methodInfo == null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(methodInfo); var parameters = methodInfo.GetParameters(); var values = new object?[parameters.Length]; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/PhysicalFileResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/PhysicalFileResultExecutor.cs index 4e339c2acf90..31bb34e9640b 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/PhysicalFileResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/PhysicalFileResultExecutor.cs @@ -25,15 +25,8 @@ public PhysicalFileResultExecutor(ILoggerFactory loggerFactory) /// public virtual Task ExecuteAsync(ActionContext context, PhysicalFileResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var fileInfo = GetFileInfo(result.FileName); if (!fileInfo.Exists) @@ -74,15 +67,8 @@ internal static Task WriteFileAsyncInternal( long rangeLength, ILogger logger) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(result); if (range != null && rangeLength == 0) { @@ -118,10 +104,7 @@ internal static Task WriteFileAsyncInternal( [Obsolete("This API is no longer called.")] protected virtual Stream GetFileStream(string path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); return new FileStream( path, diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectResultExecutor.cs index 5cf974f9cc33..710f9ccb6e58 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectResultExecutor.cs @@ -22,15 +22,8 @@ public partial class RedirectResultExecutor : IActionResultExecutorThe factory used to create url helpers. public RedirectResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory urlHelperFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(urlHelperFactory); _logger = loggerFactory.CreateLogger(); _urlHelperFactory = urlHelperFactory; @@ -39,15 +32,8 @@ public RedirectResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory ur /// public virtual Task ExecuteAsync(ActionContext context, RedirectResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToActionResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToActionResultExecutor.cs index c32f97d18b89..7c85510460b2 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToActionResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToActionResultExecutor.cs @@ -23,15 +23,8 @@ public partial class RedirectToActionResultExecutor : IActionResultExecutorThe factory used to create url helpers. public RedirectToActionResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory urlHelperFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(urlHelperFactory); _logger = loggerFactory.CreateLogger(); _urlHelperFactory = urlHelperFactory; @@ -40,15 +33,8 @@ public RedirectToActionResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFa /// public virtual Task ExecuteAsync(ActionContext context, RedirectToActionResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToPageResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToPageResultExecutor.cs index e90904d8b348..9345b1df6413 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToPageResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToPageResultExecutor.cs @@ -23,15 +23,8 @@ public partial class RedirectToPageResultExecutor : IActionResultExecutorThe factory used to create url helpers. public RedirectToPageResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory urlHelperFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(urlHelperFactory); _logger = loggerFactory.CreateLogger(); _urlHelperFactory = urlHelperFactory; @@ -40,15 +33,8 @@ public RedirectToPageResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFact /// public virtual Task ExecuteAsync(ActionContext context, RedirectToPageResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); var destinationUrl = urlHelper.Page( diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToRouteResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToRouteResultExecutor.cs index 7ce084d57e4b..81a13ab6992b 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToRouteResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/RedirectToRouteResultExecutor.cs @@ -23,15 +23,8 @@ public partial class RedirectToRouteResultExecutor : IActionResultExecutorThe factory used to create url helpers. public RedirectToRouteResultExecutor(ILoggerFactory loggerFactory, IUrlHelperFactory urlHelperFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(urlHelperFactory); _logger = loggerFactory.CreateLogger(); _urlHelperFactory = urlHelperFactory; diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs index a03d2bae6db3..c905ff9cabee 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs @@ -33,15 +33,8 @@ public SystemTextJsonResultExecutor( public async Task ExecuteAsync(ActionContext context, JsonResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var jsonSerializerOptions = GetSerializerOptions(result); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/TypeActivatorCache.cs b/src/Mvc/Mvc.Core/src/Infrastructure/TypeActivatorCache.cs index 861ba505c505..7c31b346bb16 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/TypeActivatorCache.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/TypeActivatorCache.cs @@ -22,15 +22,8 @@ public TInstance CreateInstance( IServiceProvider serviceProvider, Type implementationType) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(implementationType); var createFactory = _typeActivatorCache.GetOrAdd(implementationType, _createFactory); return (TInstance)createFactory(serviceProvider, arguments: null); diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/VirtualFileResultExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/VirtualFileResultExecutor.cs index 56180487e5f0..d76cda9fa3c5 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/VirtualFileResultExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/VirtualFileResultExecutor.cs @@ -25,10 +25,7 @@ public partial class VirtualFileResultExecutor : FileResultExecutorBase, IAction public VirtualFileResultExecutor(ILoggerFactory loggerFactory, IWebHostEnvironment hostingEnvironment) : base(CreateLogger(loggerFactory)) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); _hostingEnvironment = hostingEnvironment; } @@ -36,15 +33,8 @@ public VirtualFileResultExecutor(ILoggerFactory loggerFactory, IWebHostEnvironme /// public virtual Task ExecuteAsync(ActionContext context, VirtualFileResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var fileInfo = GetFileInformation(result, _hostingEnvironment); if (!fileInfo.Exists) @@ -75,15 +65,8 @@ public virtual Task ExecuteAsync(ActionContext context, VirtualFileResult result /// protected virtual Task WriteFileAsync(ActionContext context, VirtualFileResult result, IFileInfo fileInfo, RangeItemHeaderValue? range, long rangeLength) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); return WriteFileAsyncInternal(context.HttpContext, fileInfo, range, rangeLength, Logger); } diff --git a/src/Mvc/Mvc.Core/src/JsonResult.cs b/src/Mvc/Mvc.Core/src/JsonResult.cs index be671ad3b0a0..523d3cd851ba 100644 --- a/src/Mvc/Mvc.Core/src/JsonResult.cs +++ b/src/Mvc/Mvc.Core/src/JsonResult.cs @@ -69,10 +69,7 @@ public JsonResult(object? value, object? serializerSettings) /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var services = context.HttpContext.RequestServices; var executor = services.GetRequiredService>(); diff --git a/src/Mvc/Mvc.Core/src/LocalRedirectResult.cs b/src/Mvc/Mvc.Core/src/LocalRedirectResult.cs index 2608ee8af55d..a5a8ad42a408 100644 --- a/src/Mvc/Mvc.Core/src/LocalRedirectResult.cs +++ b/src/Mvc/Mvc.Core/src/LocalRedirectResult.cs @@ -93,10 +93,7 @@ public string Url /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/ModelBinderAttribute.cs b/src/Mvc/Mvc.Core/src/ModelBinderAttribute.cs index a945d649beb9..c909c0882f60 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinderAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinderAttribute.cs @@ -46,10 +46,7 @@ public ModelBinderAttribute() /// public ModelBinderAttribute(Type binderType) { - if (binderType == null) - { - throw new ArgumentNullException(nameof(binderType)); - } + ArgumentNullException.ThrowIfNull(binderType); BinderType = binderType; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinder.cs index b315c68e22d4..c8d8295a7218 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinder.cs @@ -108,10 +108,7 @@ protected override object CreateEmptyCollection(Type targetType) /// protected override void CopyToModel(object target, IEnumerable sourceCollection) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); // Do not attempt to copy values into an array because an array's length is immutable. This choice is also // consistent with our handling of a read-only array property. diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinderProvider.cs index dd1770c284fd..8051e64e6c0e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ArrayModelBinderProvider.cs @@ -17,10 +17,7 @@ public class ArrayModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.ModelType.IsArray) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinder.cs index 2ab12fd7240d..d9807fa6d76f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinder.cs @@ -22,10 +22,7 @@ public class BinderTypeModelBinder : IModelBinder /// The of the . public BinderTypeModelBinder(Type binderType) { - if (binderType == null) - { - throw new ArgumentNullException(nameof(binderType)); - } + ArgumentNullException.ThrowIfNull(binderType); if (!typeof(IModelBinder).IsAssignableFrom(binderType)) { @@ -42,10 +39,7 @@ public BinderTypeModelBinder(Type binderType) /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); var requestServices = bindingContext.HttpContext.RequestServices; var binder = (IModelBinder)_factory(requestServices, arguments: null); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs index 952b73238453..74371f9c39a8 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BinderTypeModelBinderProvider.cs @@ -14,10 +14,7 @@ public class BinderTypeModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.BindingInfo.BinderType is Type binderType) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs index 2460b32ac703..8f6162b0bf41 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinder.cs @@ -70,15 +70,8 @@ public BodyModelBinder( ILoggerFactory? loggerFactory, MvcOptions? options) { - if (formatters == null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (readerFactory == null) - { - throw new ArgumentNullException(nameof(readerFactory)); - } + ArgumentNullException.ThrowIfNull(formatters); + ArgumentNullException.ThrowIfNull(readerFactory); _formatters = formatters; _readerFactory = readerFactory.CreateReader; @@ -93,10 +86,7 @@ public BodyModelBinder( /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinderProvider.cs index b10d437524a4..6f88b4911674 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/BodyModelBinderProvider.cs @@ -55,15 +55,8 @@ public BodyModelBinderProvider( ILoggerFactory loggerFactory, MvcOptions? options) { - if (formatters == null) - { - throw new ArgumentNullException(nameof(formatters)); - } - - if (readerFactory == null) - { - throw new ArgumentNullException(nameof(readerFactory)); - } + ArgumentNullException.ThrowIfNull(formatters); + ArgumentNullException.ThrowIfNull(readerFactory); _formatters = formatters; _readerFactory = readerFactory; @@ -74,10 +67,7 @@ public BodyModelBinderProvider( /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.BindingInfo.BindingSource != null && context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Body)) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinder.cs index 4c676f55eb4c..3143bfaff27c 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinder.cs @@ -20,10 +20,7 @@ public class ByteArrayModelBinder : IModelBinder /// The . public ByteArrayModelBinder(ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } @@ -31,10 +28,7 @@ public ByteArrayModelBinder(ILoggerFactory loggerFactory) /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinderProvider.cs index 6e401793211d..81f3b53d250e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ByteArrayModelBinderProvider.cs @@ -16,10 +16,7 @@ public class ByteArrayModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.ModelType == typeof(byte[])) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinder.cs index f58d2dfe635b..21a3f63364f3 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinder.cs @@ -15,10 +15,7 @@ public class CancellationTokenModelBinder : IModelBinder /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); // We need to force boxing now, so we can insert the same reference to the boxed CancellationToken // in both the ValidationState and ModelBindingResult. diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinderProvider.cs index 7b473bce5e0c..fb43bb01731b 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CancellationTokenModelBinderProvider.cs @@ -17,10 +17,7 @@ public class CancellationTokenModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.ModelType == typeof(CancellationToken)) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinder.cs index fc84bfe42d6e..6d4a65960d4f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinder.cs @@ -54,15 +54,8 @@ public CollectionModelBinder( ILoggerFactory loggerFactory, bool allowValidatingTopLevelNodes) { - if (elementBinder == null) - { - throw new ArgumentNullException(nameof(elementBinder)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(elementBinder); + ArgumentNullException.ThrowIfNull(loggerFactory); ElementBinder = elementBinder; Logger = loggerFactory.CreateLogger(GetType()); @@ -90,10 +83,7 @@ public CollectionModelBinder( MvcOptions mvcOptions) : this(elementBinder, loggerFactory, allowValidatingTopLevelNodes) { - if (mvcOptions == null) - { - throw new ArgumentNullException(nameof(mvcOptions)); - } + ArgumentNullException.ThrowIfNull(mvcOptions); _maxModelBindingCollectionSize = mvcOptions.MaxModelBindingCollectionSize; } @@ -114,10 +104,7 @@ public CollectionModelBinder( /// public virtual async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Logger.AttemptingToBindModel(bindingContext); @@ -465,10 +452,7 @@ internal sealed record CollectionResult(IEnumerable Model) /// protected virtual void CopyToModel(object target, IEnumerable sourceCollection) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); var targetCollection = target as ICollection; Debug.Assert(targetCollection != null, "This binder is instantiated only for ICollection model types."); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinderProvider.cs index 71d7fda2dec3..aa26ff8a4bf5 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/CollectionModelBinderProvider.cs @@ -18,10 +18,7 @@ public class CollectionModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.ModelType; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs index b3740b533758..cc0fd9f2db07 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinder.cs @@ -48,10 +48,7 @@ internal ComplexObjectModelBinder( /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); @@ -180,10 +177,7 @@ internal static bool CreateModel(ModelBindingContext bindingContext, ModelMetada /// An compatible with . internal void CreateModel(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); // If model creator throws an exception, we want to propagate it back up the call stack, since the // application developer should know that this was an invalid type to try to bind to. diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinderProvider.cs index 1cc25cd60774..811b69375d1b 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexObjectModelBinderProvider.cs @@ -16,10 +16,7 @@ public class ComplexObjectModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var metadata = context.Metadata; if (metadata.IsComplexType && !metadata.IsCollectionType) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinder.cs index c72769f52cd9..eae49f7d43ae 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinder.cs @@ -67,15 +67,8 @@ public ComplexTypeModelBinder( ILoggerFactory loggerFactory, bool allowValidatingTopLevelNodes) { - if (propertyBinders == null) - { - throw new ArgumentNullException(nameof(propertyBinders)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(propertyBinders); + ArgumentNullException.ThrowIfNull(loggerFactory); _propertyBinders = propertyBinders; _logger = loggerFactory.CreateLogger(); @@ -84,10 +77,7 @@ public ComplexTypeModelBinder( /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); @@ -468,10 +458,7 @@ private static bool CanUpdateReadOnlyProperty(Type propertyType) /// An compatible with . protected virtual object CreateModel(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); // If model creator throws an exception, we want to propagate it back up the call stack, since the // application developer should know that this was an invalid type to try to bind to. @@ -534,20 +521,9 @@ protected virtual void SetProperty( ModelMetadata propertyMetadata, ModelBindingResult result) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } - - if (modelName == null) - { - throw new ArgumentNullException(nameof(modelName)); - } - - if (propertyMetadata == null) - { - throw new ArgumentNullException(nameof(propertyMetadata)); - } + ArgumentNullException.ThrowIfNull(bindingContext); + ArgumentNullException.ThrowIfNull(modelName); + ArgumentNullException.ThrowIfNull(propertyMetadata); if (!result.IsModelSet) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinderProvider.cs index 8f17a059ac49..5336e9e41095 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinderProvider.cs @@ -17,10 +17,7 @@ public class ComplexTypeModelBinderProvider : IModelBinderProvider /// public IModelBinder GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinder.cs index a4b237182080..875139e33382 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinder.cs @@ -23,10 +23,7 @@ public class DateTimeModelBinder : IModelBinder /// The . public DateTimeModelBinder(DateTimeStyles supportedStyles, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _supportedStyles = supportedStyles; _logger = loggerFactory.CreateLogger(); @@ -35,10 +32,7 @@ public DateTimeModelBinder(DateTimeStyles supportedStyles, ILoggerFactory logger /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs index dabe1233e141..48db6951b79a 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DateTimeModelBinderProvider.cs @@ -19,10 +19,7 @@ public class DateTimeModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.UnderlyingOrModelType; if (modelType == typeof(DateTime)) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DecimalModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DecimalModelBinder.cs index 210223390fdf..cb3c228919b6 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DecimalModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DecimalModelBinder.cs @@ -25,10 +25,7 @@ public class DecimalModelBinder : IModelBinder /// The . public DecimalModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _supportedStyles = supportedStyles; _logger = loggerFactory.CreateLogger(); @@ -37,10 +34,7 @@ public DecimalModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFac /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinder.cs index 36c97f95236f..9188a90ee7bb 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinder.cs @@ -28,10 +28,7 @@ public partial class DictionaryModelBinder : CollectionModelBinder public DictionaryModelBinder(IModelBinder keyBinder, IModelBinder valueBinder, ILoggerFactory loggerFactory) : base(new KeyValuePairModelBinder(keyBinder, valueBinder, loggerFactory), loggerFactory) { - if (valueBinder == null) - { - throw new ArgumentNullException(nameof(valueBinder)); - } + ArgumentNullException.ThrowIfNull(valueBinder); _valueBinder = valueBinder; } @@ -65,10 +62,7 @@ public DictionaryModelBinder( // CollectionModelBinder should not check IsRequired, done in this model binder. allowValidatingTopLevelNodes: false) { - if (valueBinder == null) - { - throw new ArgumentNullException(nameof(valueBinder)); - } + ArgumentNullException.ThrowIfNull(valueBinder); _valueBinder = valueBinder; } @@ -107,10 +101,7 @@ public DictionaryModelBinder( allowValidatingTopLevelNodes: false, mvcOptions) { - if (valueBinder == null) - { - throw new ArgumentNullException(nameof(valueBinder)); - } + ArgumentNullException.ThrowIfNull(valueBinder); _valueBinder = valueBinder; } @@ -118,10 +109,7 @@ public DictionaryModelBinder( /// public override async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); await base.BindModelAsync(bindingContext); if (!bindingContext.Result.IsModelSet) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinderProvider.cs index f59eedb93614..a727b6014082 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DictionaryModelBinderProvider.cs @@ -18,10 +18,7 @@ public class DictionaryModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.ModelType; var dictionaryType = ClosedGenericMatcher.ExtractGenericInterface(modelType, typeof(IDictionary<,>)); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DoubleModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DoubleModelBinder.cs index 5dd02fa90296..9920257773d7 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DoubleModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/DoubleModelBinder.cs @@ -25,10 +25,7 @@ public class DoubleModelBinder : IModelBinder /// The . public DoubleModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _supportedStyles = supportedStyles; _logger = loggerFactory.CreateLogger(); @@ -37,10 +34,7 @@ public DoubleModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFact /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/EnumTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/EnumTypeModelBinderProvider.cs index b658e2914830..6740a2b4e56a 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/EnumTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/EnumTypeModelBinderProvider.cs @@ -25,10 +25,7 @@ public EnumTypeModelBinderProvider(MvcOptions options) /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.IsEnum) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatModelBinder.cs index 7f48b7b88f01..3403ec3b8f1c 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatModelBinder.cs @@ -25,10 +25,7 @@ public class FloatModelBinder : IModelBinder /// The . public FloatModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _supportedStyles = supportedStyles; _logger = loggerFactory.CreateLogger(); @@ -37,10 +34,7 @@ public FloatModelBinder(NumberStyles supportedStyles, ILoggerFactory loggerFacto /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs index 35356a4f6211..e28b52a21984 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FloatingPointTypeModelBinderProvider.cs @@ -22,10 +22,7 @@ public class FloatingPointTypeModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.UnderlyingOrModelType; var loggerFactory = context.Services.GetRequiredService(); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinder.cs index 75839bfe5e42..22b645275275 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinder.cs @@ -24,10 +24,7 @@ public class FormCollectionModelBinder : IModelBinder /// The . public FormCollectionModelBinder(ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } @@ -35,10 +32,7 @@ public FormCollectionModelBinder(ILoggerFactory loggerFactory) /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinderProvider.cs index 6881805c183e..c93ae6209317 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormCollectionModelBinderProvider.cs @@ -18,10 +18,7 @@ public class FormCollectionModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.ModelType; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinder.cs index 601096a6d146..53029aa98ebd 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinder.cs @@ -25,10 +25,7 @@ public partial class FormFileModelBinder : IModelBinder /// The . public FormFileModelBinder(ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } @@ -36,10 +33,7 @@ public FormFileModelBinder(ILoggerFactory loggerFactory) /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinderProvider.cs index 319e7df89e7e..835ad7d92641 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinderProvider.cs @@ -18,10 +18,7 @@ public class FormFileModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Note: This condition needs to be kept in sync with ApiBehaviorApplicationModelProvider. var modelType = context.Metadata.ModelType; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinder.cs index 1b81ede943d6..b61eeaace214 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinder.cs @@ -35,15 +35,8 @@ public HeaderModelBinder(ILoggerFactory loggerFactory) /// binding of values. public HeaderModelBinder(ILoggerFactory loggerFactory, IModelBinder innerModelBinder) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (innerModelBinder == null) - { - throw new ArgumentNullException(nameof(innerModelBinder)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(innerModelBinder); _logger = loggerFactory.CreateLogger(); InnerModelBinder = innerModelBinder; @@ -55,10 +48,7 @@ public HeaderModelBinder(ILoggerFactory loggerFactory, IModelBinder innerModelBi /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinderProvider.cs index fd29db9b64c4..e34f6dfae79b 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/HeaderModelBinderProvider.cs @@ -16,10 +16,7 @@ public partial class HeaderModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var bindingInfo = context.BindingInfo; if (bindingInfo.BindingSource == null || diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinder.cs index 3cea20424fa7..5cff0c8043d9 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinder.cs @@ -26,20 +26,9 @@ public class KeyValuePairModelBinder : IModelBinder /// The . public KeyValuePairModelBinder(IModelBinder keyBinder, IModelBinder valueBinder, ILoggerFactory loggerFactory) { - if (keyBinder == null) - { - throw new ArgumentNullException(nameof(keyBinder)); - } - - if (valueBinder == null) - { - throw new ArgumentNullException(nameof(valueBinder)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(keyBinder); + ArgumentNullException.ThrowIfNull(valueBinder); + ArgumentNullException.ThrowIfNull(loggerFactory); _keyBinder = keyBinder; _valueBinder = valueBinder; @@ -49,10 +38,7 @@ public KeyValuePairModelBinder(IModelBinder keyBinder, IModelBinder valueBinder, /// public async Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinderProvider.cs index e6a430239d1e..489779da3de2 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/KeyValuePairModelBinderProvider.cs @@ -16,10 +16,7 @@ public class KeyValuePairModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.Metadata.ModelType; if (modelType.IsGenericType && diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinder.cs index d9ce45170d66..f40627bd1226 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinder.cs @@ -19,10 +19,7 @@ public class ServicesModelBinder : IModelBinder /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); var requestServices = bindingContext.HttpContext.RequestServices; var model = IsOptional ? diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinderProvider.cs index 92d06f51414c..6dc30fb4952c 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/ServicesModelBinderProvider.cs @@ -18,10 +18,7 @@ public class ServicesModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.BindingInfo.BindingSource != null && context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Services)) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinder.cs index f80caaa3d3ee..323774fb763f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinder.cs @@ -24,15 +24,8 @@ public class SimpleTypeModelBinder : IModelBinder /// The . public SimpleTypeModelBinder(Type type, ILoggerFactory loggerFactory) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(loggerFactory); _typeConverter = TypeDescriptor.GetConverter(type); _logger = loggerFactory.CreateLogger(); @@ -41,10 +34,7 @@ public SimpleTypeModelBinder(Type type, ILoggerFactory loggerFactory) /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinderProvider.cs index e969919ee513..695cb25c9e14 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/SimpleTypeModelBinderProvider.cs @@ -16,10 +16,7 @@ public class SimpleTypeModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.Metadata.IsComplexType) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinder.cs index 2339d786c054..ea47231cdeec 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinder.cs @@ -32,15 +32,8 @@ internal sealed class TryParseModelBinder : IModelBinder /// The . public TryParseModelBinder(Type modelType, ILoggerFactory loggerFactory) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(loggerFactory); _tryParseOperation = CreateTryParseOperation(modelType); _logger = loggerFactory.CreateLogger(); @@ -49,10 +42,7 @@ public TryParseModelBinder(Type modelType, ILoggerFactory loggerFactory) /// public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); _logger.AttemptingToBindModel(bindingContext); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinderProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinderProvider.cs index e41c21640f5c..40a79e49d49c 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinderProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Binders/TryParseModelBinderProvider.cs @@ -14,10 +14,7 @@ public sealed class TryParseModelBinderProvider : IModelBinderProvider /// public IModelBinder? GetBinder(ModelBinderProviderContext context) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.IsParseableType) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/BindingSourceValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/BindingSourceValueProvider.cs index 8d64366bcec7..07b58c855a63 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/BindingSourceValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/BindingSourceValueProvider.cs @@ -34,10 +34,7 @@ public abstract class BindingSourceValueProvider : IBindingSourceValueProvider /// public BindingSourceValueProvider(BindingSource bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } + ArgumentNullException.ThrowIfNull(bindingSource); if (bindingSource.IsGreedy) { @@ -72,10 +69,7 @@ public BindingSourceValueProvider(BindingSource bindingSource) /// public virtual IValueProvider? Filter(BindingSource bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } + ArgumentNullException.ThrowIfNull(bindingSource); if (bindingSource.CanAcceptDataFrom(BindingSource)) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/CompositeValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/CompositeValueProvider.cs index d7fdd146a9d9..020135be0c9c 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/CompositeValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/CompositeValueProvider.cs @@ -44,10 +44,7 @@ public CompositeValueProvider(IList valueProviders) /// public static async Task CreateAsync(ControllerContext controllerContext) { - if (controllerContext == null) - { - throw new ArgumentNullException(nameof(controllerContext)); - } + ArgumentNullException.ThrowIfNull(controllerContext); var factories = controllerContext.ValueProviderFactories; @@ -147,10 +144,7 @@ public virtual IDictionary GetKeysFromPrefix(string prefix) /// protected override void InsertItem(int index, IValueProvider item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } @@ -158,10 +152,7 @@ protected override void InsertItem(int index, IValueProvider item) /// protected override void SetItem(int index, IValueProvider item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); } @@ -169,10 +160,7 @@ protected override void SetItem(int index, IValueProvider item) /// public IValueProvider? Filter(BindingSource bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } + ArgumentNullException.ThrowIfNull(bindingSource); var shouldFilter = false; for (var i = 0; i < Count; i++) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/DefaultModelBindingContext.cs b/src/Mvc/Mvc.Core/src/ModelBinding/DefaultModelBindingContext.cs index f307e2f5a819..d196cb96c926 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/DefaultModelBindingContext.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/DefaultModelBindingContext.cs @@ -32,10 +32,7 @@ public override ActionContext ActionContext get { return _actionContext; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _actionContext = value; } } @@ -46,10 +43,7 @@ public override string FieldName get { return _state.FieldName; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _state.FieldName = value; } } @@ -67,10 +61,7 @@ public override ModelMetadata ModelMetadata get { return _state.ModelMetadata; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _state.ModelMetadata = value; } } @@ -81,10 +72,7 @@ public override string ModelName get { return _state.ModelName; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _state.ModelName = value; } } @@ -95,10 +83,7 @@ public override ModelStateDictionary ModelState get { return _modelState; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _modelState = value; } } @@ -132,10 +117,7 @@ public IValueProvider OriginalValueProvider get { return _originalValueProvider; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _originalValueProvider = value; } } @@ -146,10 +128,7 @@ public override IValueProvider ValueProvider get { return _state.ValueProvider; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _state.ValueProvider = value; } } @@ -167,10 +146,7 @@ public override ValidationStateDictionary ValidationState get { return _validationState; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _validationState = value; } } @@ -225,25 +201,10 @@ public static ModelBindingContext CreateBindingContext( BindingInfo? bindingInfo, string modelName) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - - if (modelName == null) - { - throw new ArgumentNullException(nameof(modelName)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(modelName); var binderModelName = bindingInfo?.BinderModelName ?? metadata.BinderModelName; var bindingSource = bindingInfo?.BindingSource ?? metadata.BindingSource; @@ -287,20 +248,9 @@ public override NestedScope EnterNestedScope( string modelName, object? model) { - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } - - if (fieldName == null) - { - throw new ArgumentNullException(nameof(fieldName)); - } - - if (modelName == null) - { - throw new ArgumentNullException(nameof(modelName)); - } + ArgumentNullException.ThrowIfNull(modelMetadata); + ArgumentNullException.ThrowIfNull(fieldName); + ArgumentNullException.ThrowIfNull(modelName); var scope = EnterNestedScope(); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/FormFileValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/FormFileValueProviderFactory.cs index b74766de892d..2c4be9667efd 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/FormFileValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/FormFileValueProviderFactory.cs @@ -16,10 +16,7 @@ public sealed class FormFileValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var request = context.ActionContext.HttpContext.Request; if (request.HasFormContentType) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProvider.cs index 6c1d91854974..cfaccee3ce54 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProvider.cs @@ -29,15 +29,8 @@ public FormValueProvider( CultureInfo? culture) : base(bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(bindingSource); + ArgumentNullException.ThrowIfNull(values); _values = values; @@ -79,10 +72,7 @@ public override bool ContainsPrefix(string prefix) /// public virtual IDictionary GetKeysFromPrefix(string prefix) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(prefix); return PrefixContainer.GetKeysFromPrefix(prefix); } @@ -90,10 +80,7 @@ public virtual IDictionary GetKeysFromPrefix(string prefix) /// public override ValueProviderResult GetValue(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (key.Length == 0) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProviderFactory.cs index 18bebb69b49c..cd62315ec604 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/FormValueProviderFactory.cs @@ -17,10 +17,7 @@ public class FormValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var request = context.ActionContext.HttpContext.Request; if (request.HasFormContentType) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryFormValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryFormValueProviderFactory.cs index 48bfa06c5c57..b5a234b3f443 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryFormValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryFormValueProviderFactory.cs @@ -17,10 +17,7 @@ public class JQueryFormValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var request = context.ActionContext.HttpContext.Request; if (request.HasFormContentType) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryQueryStringValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryQueryStringValueProviderFactory.cs index 96374e60cd26..531652eeb869 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryQueryStringValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryQueryStringValueProviderFactory.cs @@ -15,10 +15,7 @@ public class JQueryQueryStringValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var query = context.ActionContext.HttpContext.Request.Query; if (query != null && query.Count > 0) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryValueProvider.cs index 6a2960289b3a..7e28ee31653f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/JQueryValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/JQueryValueProvider.cs @@ -31,15 +31,8 @@ protected JQueryValueProvider( CultureInfo? culture) : base(bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(bindingSource); + ArgumentNullException.ThrowIfNull(values); _values = values; Culture = culture; @@ -79,10 +72,7 @@ public IDictionary GetKeysFromPrefix(string prefix) /// public override ValueProviderResult GetValue(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (_values.TryGetValue(key, out var values) && values.Count > 0) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadata.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadata.cs index e3b1fab3f53a..adfba1910970 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadata.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadata.cs @@ -87,10 +87,7 @@ public DefaultModelBindingMessageProvider? ModelBindingMessageProvider get => _messageProvider; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _messageProvider = value; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadataProviderContext.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadataProviderContext.cs index 8bc2991008d1..258f1388771e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadataProviderContext.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingMetadataProviderContext.cs @@ -19,10 +19,7 @@ public BindingMetadataProviderContext( ModelMetadataIdentity key, ModelAttributes attributes) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); Key = key; Attributes = attributes.Attributes; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingSourceMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingSourceMetadataProvider.cs index 7cd03bb9d6e9..8718c64c6f33 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingSourceMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/BindingSourceMetadataProvider.cs @@ -22,10 +22,7 @@ public class BindingSourceMetadataProvider : IBindingMetadataProvider /// public BindingSourceMetadataProvider(Type type, BindingSource? bindingSource) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); Type = type; BindingSource = bindingSource; @@ -45,10 +42,7 @@ public BindingSourceMetadataProvider(Type type, BindingSource? bindingSource) /// public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (Type.IsAssignableFrom(context.Key.ModelType)) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultBindingMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultBindingMetadataProvider.cs index 376c57a2e8a1..90eb0b9eb208 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultBindingMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultBindingMetadataProvider.cs @@ -16,10 +16,7 @@ internal sealed class DefaultBindingMetadataProvider : IBindingMetadataProvider { public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // BinderModelName foreach (var binderModelNameAttribute in context.Attributes.OfType()) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultCompositeMetadataDetailsProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultCompositeMetadataDetailsProvider.cs index 2dc812bb5dd5..dda70d1d167e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultCompositeMetadataDetailsProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultCompositeMetadataDetailsProvider.cs @@ -28,10 +28,7 @@ public DefaultCompositeMetadataDetailsProvider(IEnumerable public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var provider in _providers.OfType()) { @@ -42,10 +39,7 @@ public void CreateBindingMetadata(BindingMetadataProviderContext context) /// public void CreateDisplayMetadata(DisplayMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var provider in _providers.OfType()) { @@ -56,10 +50,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var provider in _providers.OfType()) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultMetadataDetails.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultMetadataDetails.cs index 6a3c5d34c8f8..a1536f8692c0 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultMetadataDetails.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultMetadataDetails.cs @@ -20,10 +20,7 @@ public class DefaultMetadataDetails /// The set of model attributes. public DefaultMetadataDetails(ModelMetadataIdentity key, ModelAttributes attributes) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); Key = key; ModelAttributes = attributes; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelBindingMessageProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelBindingMessageProvider.cs index 7ce35fef2c49..dfb68547620f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelBindingMessageProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelBindingMessageProvider.cs @@ -50,10 +50,7 @@ public DefaultModelBindingMessageProvider() /// The to duplicate. public DefaultModelBindingMessageProvider(DefaultModelBindingMessageProvider originalProvider) { - if (originalProvider == null) - { - throw new ArgumentNullException(nameof(originalProvider)); - } + ArgumentNullException.ThrowIfNull(originalProvider); SetMissingBindRequiredValueAccessor(originalProvider.MissingBindRequiredValueAccessor); SetMissingKeyOrValueAccessor(originalProvider.MissingKeyOrValueAccessor); @@ -78,10 +75,7 @@ public DefaultModelBindingMessageProvider(DefaultModelBindingMessageProvider ori [MemberNotNull(nameof(_missingBindRequiredValueAccessor))] public void SetMissingBindRequiredValueAccessor(Func missingBindRequiredValueAccessor) { - if (missingBindRequiredValueAccessor == null) - { - throw new ArgumentNullException(nameof(missingBindRequiredValueAccessor)); - } + ArgumentNullException.ThrowIfNull(missingBindRequiredValueAccessor); _missingBindRequiredValueAccessor = missingBindRequiredValueAccessor; } @@ -96,10 +90,7 @@ public void SetMissingBindRequiredValueAccessor(Func missingBind [MemberNotNull(nameof(_missingKeyOrValueAccessor))] public void SetMissingKeyOrValueAccessor(Func missingKeyOrValueAccessor) { - if (missingKeyOrValueAccessor == null) - { - throw new ArgumentNullException(nameof(missingKeyOrValueAccessor)); - } + ArgumentNullException.ThrowIfNull(missingKeyOrValueAccessor); _missingKeyOrValueAccessor = missingKeyOrValueAccessor; } @@ -114,10 +105,7 @@ public void SetMissingKeyOrValueAccessor(Func missingKeyOrValueAccessor) [MemberNotNull(nameof(_missingRequestBodyRequiredValueAccessor))] public void SetMissingRequestBodyRequiredValueAccessor(Func missingRequestBodyRequiredValueAccessor) { - if (missingRequestBodyRequiredValueAccessor == null) - { - throw new ArgumentNullException(nameof(missingRequestBodyRequiredValueAccessor)); - } + ArgumentNullException.ThrowIfNull(missingRequestBodyRequiredValueAccessor); _missingRequestBodyRequiredValueAccessor = missingRequestBodyRequiredValueAccessor; } @@ -132,10 +120,7 @@ public void SetMissingRequestBodyRequiredValueAccessor(Func missingReque [MemberNotNull(nameof(_valueMustNotBeNullAccessor))] public void SetValueMustNotBeNullAccessor(Func valueMustNotBeNullAccessor) { - if (valueMustNotBeNullAccessor == null) - { - throw new ArgumentNullException(nameof(valueMustNotBeNullAccessor)); - } + ArgumentNullException.ThrowIfNull(valueMustNotBeNullAccessor); _valueMustNotBeNullAccessor = valueMustNotBeNullAccessor; } @@ -150,10 +135,7 @@ public void SetValueMustNotBeNullAccessor(Func valueMustNotBeNul [MemberNotNull(nameof(_attemptedValueIsInvalidAccessor))] public void SetAttemptedValueIsInvalidAccessor(Func attemptedValueIsInvalidAccessor) { - if (attemptedValueIsInvalidAccessor == null) - { - throw new ArgumentNullException(nameof(attemptedValueIsInvalidAccessor)); - } + ArgumentNullException.ThrowIfNull(attemptedValueIsInvalidAccessor); _attemptedValueIsInvalidAccessor = attemptedValueIsInvalidAccessor; } @@ -169,10 +151,7 @@ public void SetAttemptedValueIsInvalidAccessor(Func atte public void SetNonPropertyAttemptedValueIsInvalidAccessor( Func nonPropertyAttemptedValueIsInvalidAccessor) { - if (nonPropertyAttemptedValueIsInvalidAccessor == null) - { - throw new ArgumentNullException(nameof(nonPropertyAttemptedValueIsInvalidAccessor)); - } + ArgumentNullException.ThrowIfNull(nonPropertyAttemptedValueIsInvalidAccessor); _nonPropertyAttemptedValueIsInvalidAccessor = nonPropertyAttemptedValueIsInvalidAccessor; } @@ -187,10 +166,7 @@ public void SetNonPropertyAttemptedValueIsInvalidAccessor( [MemberNotNull(nameof(_unknownValueIsInvalidAccessor))] public void SetUnknownValueIsInvalidAccessor(Func unknownValueIsInvalidAccessor) { - if (unknownValueIsInvalidAccessor == null) - { - throw new ArgumentNullException(nameof(unknownValueIsInvalidAccessor)); - } + ArgumentNullException.ThrowIfNull(unknownValueIsInvalidAccessor); _unknownValueIsInvalidAccessor = unknownValueIsInvalidAccessor; } @@ -205,10 +181,7 @@ public void SetUnknownValueIsInvalidAccessor(Func unknownValueIs [MemberNotNull(nameof(_nonPropertyUnknownValueIsInvalidAccessor))] public void SetNonPropertyUnknownValueIsInvalidAccessor(Func nonPropertyUnknownValueIsInvalidAccessor) { - if (nonPropertyUnknownValueIsInvalidAccessor == null) - { - throw new ArgumentNullException(nameof(nonPropertyUnknownValueIsInvalidAccessor)); - } + ArgumentNullException.ThrowIfNull(nonPropertyUnknownValueIsInvalidAccessor); _nonPropertyUnknownValueIsInvalidAccessor = nonPropertyUnknownValueIsInvalidAccessor; } @@ -223,10 +196,7 @@ public void SetNonPropertyUnknownValueIsInvalidAccessor(Func nonProperty [MemberNotNull(nameof(_valueIsInvalidAccessor))] public void SetValueIsInvalidAccessor(Func valueIsInvalidAccessor) { - if (valueIsInvalidAccessor == null) - { - throw new ArgumentNullException(nameof(valueIsInvalidAccessor)); - } + ArgumentNullException.ThrowIfNull(valueIsInvalidAccessor); _valueIsInvalidAccessor = valueIsInvalidAccessor; } @@ -241,10 +211,7 @@ public void SetValueIsInvalidAccessor(Func valueIsInvalidAccesso [MemberNotNull(nameof(_valueMustBeANumberAccessor))] public void SetValueMustBeANumberAccessor(Func valueMustBeANumberAccessor) { - if (valueMustBeANumberAccessor == null) - { - throw new ArgumentNullException(nameof(valueMustBeANumberAccessor)); - } + ArgumentNullException.ThrowIfNull(valueMustBeANumberAccessor); _valueMustBeANumberAccessor = valueMustBeANumberAccessor; } @@ -259,10 +226,7 @@ public void SetValueMustBeANumberAccessor(Func valueMustBeANumbe [MemberNotNull(nameof(_nonPropertyValueMustBeANumberAccessor))] public void SetNonPropertyValueMustBeANumberAccessor(Func nonPropertyValueMustBeANumberAccessor) { - if (nonPropertyValueMustBeANumberAccessor == null) - { - throw new ArgumentNullException(nameof(nonPropertyValueMustBeANumberAccessor)); - } + ArgumentNullException.ThrowIfNull(nonPropertyValueMustBeANumberAccessor); _nonPropertyValueMustBeANumberAccessor = nonPropertyValueMustBeANumberAccessor; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadata.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadata.cs index 429c18fef155..779b3f8d9b0e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadata.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadata.cs @@ -62,25 +62,10 @@ public DefaultModelMetadata( DefaultModelBindingMessageProvider modelBindingMessageProvider) : base(details.Key) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (detailsProvider == null) - { - throw new ArgumentNullException(nameof(detailsProvider)); - } - - if (details == null) - { - throw new ArgumentNullException(nameof(details)); - } - - if (modelBindingMessageProvider == null) - { - throw new ArgumentNullException(nameof(modelBindingMessageProvider)); - } + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(detailsProvider); + ArgumentNullException.ThrowIfNull(details); + ArgumentNullException.ThrowIfNull(modelBindingMessageProvider); _provider = provider; _detailsProvider = detailsProvider; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadataProvider.cs index 849ef20dd42d..74b3bf474c20 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultModelMetadataProvider.cs @@ -46,10 +46,7 @@ private DefaultModelMetadataProvider( ICompositeMetadataDetailsProvider detailsProvider, DefaultModelBindingMessageProvider modelBindingMessageProvider) { - if (detailsProvider == null) - { - throw new ArgumentNullException(nameof(detailsProvider)); - } + ArgumentNullException.ThrowIfNull(detailsProvider); DetailsProvider = detailsProvider; ModelBindingMessageProvider = modelBindingMessageProvider; @@ -74,10 +71,7 @@ private DefaultModelMetadataProvider( /// public override IEnumerable GetMetadataForProperties(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var cacheEntry = GetCacheEntry(modelType); @@ -108,15 +102,8 @@ public override ModelMetadata GetMetadataForParameter(ParameterInfo parameter) /// public override ModelMetadata GetMetadataForParameter(ParameterInfo parameter, Type modelType) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(parameter); + ArgumentNullException.ThrowIfNull(modelType); var cacheEntry = GetCacheEntry(parameter, modelType); @@ -126,10 +113,7 @@ public override ModelMetadata GetMetadataForParameter(ParameterInfo parameter, T /// public override ModelMetadata GetMetadataForType(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var cacheEntry = GetCacheEntry(modelType); @@ -139,15 +123,8 @@ public override ModelMetadata GetMetadataForType(Type modelType) /// public override ModelMetadata GetMetadataForProperty(PropertyInfo propertyInfo, Type modelType) { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(propertyInfo); + ArgumentNullException.ThrowIfNull(modelType); var cacheEntry = GetCacheEntry(propertyInfo, modelType); @@ -157,10 +134,7 @@ public override ModelMetadata GetMetadataForProperty(PropertyInfo propertyInfo, /// public override ModelMetadata GetMetadataForConstructor(ConstructorInfo constructorInfo, Type modelType) { - if (constructorInfo is null) - { - throw new ArgumentNullException(nameof(constructorInfo)); - } + ArgumentNullException.ThrowIfNull(constructorInfo); var cacheEntry = GetCacheEntry(constructorInfo, modelType); return cacheEntry.Metadata; @@ -168,10 +142,7 @@ public override ModelMetadata GetMetadataForConstructor(ConstructorInfo construc private static DefaultModelBindingMessageProvider GetMessageProvider(IOptions optionsAccessor) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } + ArgumentNullException.ThrowIfNull(optionsAccessor); return optionsAccessor.Value.ModelBindingMessageProvider; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultValidationMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultValidationMetadataProvider.cs index a8d7ac914e61..bb99a0d8e477 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultValidationMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DefaultValidationMetadataProvider.cs @@ -16,10 +16,7 @@ internal sealed class DefaultValidationMetadataProvider : IValidationMetadataPro /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var attribute in context.Attributes) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadata.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadata.cs index c9d6ef040cda..d779424ff623 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadata.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadata.cs @@ -72,10 +72,7 @@ public Func DisplayFormatStringProvider } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _displayFormatStringProvider = value; } @@ -134,10 +131,7 @@ public Func EditFormatStringProvider } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _editFormatStringProvider = value; } @@ -224,10 +218,7 @@ public Func NullDisplayTextProvider } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _nullDisplayTextProvider = value; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadataProviderContext.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadataProviderContext.cs index e422cfe6be83..55fa1eb64b12 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadataProviderContext.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/DisplayMetadataProviderContext.cs @@ -19,10 +19,7 @@ public DisplayMetadataProviderContext( ModelMetadataIdentity key, ModelAttributes attributes) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); Key = key; Attributes = attributes.Attributes; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ExcludeBindingMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ExcludeBindingMetadataProvider.cs index 2dc639b2d580..5318439f3f20 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ExcludeBindingMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ExcludeBindingMetadataProvider.cs @@ -22,10 +22,7 @@ public class ExcludeBindingMetadataProvider : IBindingMetadataProvider /// public ExcludeBindingMetadataProvider(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); _type = type; } @@ -33,10 +30,7 @@ public ExcludeBindingMetadataProvider(Type type) /// public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // No-op if the metadata is not for the target type if (!_type.IsAssignableFrom(context.Key.ModelType)) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/HasValidatorsValidationMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/HasValidatorsValidationMetadataProvider.cs index 3da846c07771..374f43309b33 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/HasValidatorsValidationMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/HasValidatorsValidationMetadataProvider.cs @@ -24,10 +24,7 @@ public HasValidatorsValidationMetadataProvider(IList mo public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!_hasOnlyMetadataBasedValidators) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/MetadataDetailsProviderExtensions.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/MetadataDetailsProviderExtensions.cs index 41a6bd715fa7..c25130d87a40 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/MetadataDetailsProviderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/MetadataDetailsProviderExtensions.cs @@ -17,10 +17,7 @@ public static class MetadataDetailsProviderExtensions /// The type to remove. public static void RemoveType(this IList list) where TMetadataDetailsProvider : IMetadataDetailsProvider { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); RemoveType(list, typeof(TMetadataDetailsProvider)); } @@ -32,15 +29,8 @@ public static void RemoveType(this IListThe type to remove. public static void RemoveType(this IList list, Type type) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(type); for (var i = list.Count - 1; i >= 0; i--) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ModelAttributes.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ModelAttributes.cs index 5efbd40ea42c..938af4823e9d 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ModelAttributes.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ModelAttributes.cs @@ -47,10 +47,7 @@ internal ModelAttributes( if (propertyAttributes != null) { // Represents a property - if (typeAttributes == null) - { - throw new ArgumentNullException(nameof(typeAttributes)); - } + ArgumentNullException.ThrowIfNull(typeAttributes); PropertyAttributes = propertyAttributes.ToArray(); TypeAttributes = typeAttributes.ToArray(); @@ -59,10 +56,7 @@ internal ModelAttributes( else if (parameterAttributes != null) { // Represents a parameter - if (typeAttributes == null) - { - throw new ArgumentNullException(nameof(typeAttributes)); - } + ArgumentNullException.ThrowIfNull(typeAttributes); ParameterAttributes = parameterAttributes.ToArray(); TypeAttributes = typeAttributes.ToArray(); @@ -134,15 +128,8 @@ public static ModelAttributes GetAttributesForProperty(Type type, PropertyInfo p /// public static ModelAttributes GetAttributesForProperty(Type containerType, PropertyInfo property, Type modelType) { - if (containerType == null) - { - throw new ArgumentNullException(nameof(containerType)); - } - - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } + ArgumentNullException.ThrowIfNull(containerType); + ArgumentNullException.ThrowIfNull(property); var propertyAttributes = property.GetCustomAttributes(); var typeAttributes = modelType.GetCustomAttributes(); @@ -168,10 +155,7 @@ public static ModelAttributes GetAttributesForProperty(Type containerType, Prope /// A instance with the attributes of the . public static ModelAttributes GetAttributesForType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var attributes = type.GetCustomAttributes(); @@ -216,15 +200,8 @@ public static ModelAttributes GetAttributesForParameter(ParameterInfo parameterI /// public static ModelAttributes GetAttributesForParameter(ParameterInfo parameterInfo, Type modelType) { - if (parameterInfo == null) - { - throw new ArgumentNullException(nameof(parameterInfo)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(parameterInfo); + ArgumentNullException.ThrowIfNull(modelType); // Prior versions called IModelMetadataProvider.GetMetadataForType(...) and therefore // GetAttributesForType(...) for parameters. Maintain that set of attributes (including those from an diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs index d34e6f48aa42..e9de978c9534 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs @@ -30,10 +30,7 @@ public SystemTextJsonValidationMetadataProvider() /// The to be used to configure the metadata provider. public SystemTextJsonValidationMetadataProvider(JsonNamingPolicy namingPolicy) { - if (namingPolicy == null) - { - throw new ArgumentNullException(nameof(namingPolicy)); - } + ArgumentNullException.ThrowIfNull(namingPolicy); _jsonNamingPolicy = namingPolicy; } @@ -41,10 +38,7 @@ public SystemTextJsonValidationMetadataProvider(JsonNamingPolicy namingPolicy) /// public void CreateDisplayMetadata(DisplayMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var propertyName = ReadPropertyNameFrom(context.Attributes); @@ -57,10 +51,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var propertyName = ReadPropertyNameFrom(context.Attributes); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ValidationMetadataProviderContext.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ValidationMetadataProviderContext.cs index 5bcc660d07f7..cdd91f2d8a4e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ValidationMetadataProviderContext.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ValidationMetadataProviderContext.cs @@ -19,10 +19,7 @@ public ValidationMetadataProviderContext( ModelMetadataIdentity key, ModelAttributes attributes) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); Key = key; Attributes = attributes.Attributes; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderFactory.cs index 41bb86d51381..31e3d5bebe95 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderFactory.cs @@ -50,10 +50,7 @@ public ModelBinderFactory( /// public IModelBinder CreateBinder(ModelBinderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (_providers.Length == 0) { @@ -260,15 +257,8 @@ public override IModelBinder CreateBinder(ModelMetadata metadata) public override IModelBinder CreateBinder(ModelMetadata metadata, BindingInfo bindingInfo) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - - if (bindingInfo == null) - { - throw new ArgumentNullException(nameof(bindingInfo)); - } + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(bindingInfo); // For non-root nodes we use the ModelMetadata as the cache token. This ensures that all non-root // nodes with the same metadata will have the same binder. This is OK because for an non-root diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderProviderExtensions.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderProviderExtensions.cs index ea189aefc8d6..88f96a73752f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderProviderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBinderProviderExtensions.cs @@ -17,10 +17,7 @@ public static class ModelBinderProviderExtensions /// The type to remove. public static void RemoveType(this IList list) where TModelBinderProvider : IModelBinderProvider { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); RemoveType(list, typeof(TModelBinderProvider)); } @@ -32,15 +29,8 @@ public static void RemoveType(this IListThe type to remove. public static void RemoveType(this IList list, Type type) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(type); for (var i = list.Count - 1; i >= 0; i--) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBindingHelper.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBindingHelper.cs index 34dc03f9c3bf..1b8b0642b64a 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ModelBindingHelper.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ModelBindingHelper.cs @@ -85,10 +85,7 @@ public static Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(includeExpressions); var expression = GetPropertyFilterExpression(includeExpressions); var propertyFilter = expression.Compile(); @@ -214,50 +211,15 @@ public static async Task TryUpdateModelAsync( IObjectModelValidator objectModelValidator, Func propertyFilter) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (modelBinderFactory == null) - { - throw new ArgumentNullException(nameof(modelBinderFactory)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (objectModelValidator == null) - { - throw new ArgumentNullException(nameof(objectModelValidator)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(modelBinderFactory); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(objectModelValidator); + ArgumentNullException.ThrowIfNull(propertyFilter); if (!modelType.IsAssignableFrom(model.GetType())) { @@ -405,20 +367,9 @@ public static void ClearValidationStateForModel( IModelMetadataProvider metadataProvider, string modelKey) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(metadataProvider); ClearValidationStateForModel(metadataProvider.GetMetadataForType(modelType), modelState, modelKey); } @@ -434,15 +385,8 @@ public static void ClearValidationStateForModel( ModelStateDictionary modelState, string? modelKey) { - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelMetadata); + ArgumentNullException.ThrowIfNull(modelState); if (string.IsNullOrEmpty(modelKey)) { @@ -666,10 +610,7 @@ private static List CreateList(int? capacity) /// public static object? ConvertTo(object? value, Type type, CultureInfo? culture) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (value == null) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ModelMetadataProviderExtensions.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ModelMetadataProviderExtensions.cs index d23fda2ce6b6..a2642c8a90e5 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ModelMetadataProviderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ModelMetadataProviderExtensions.cs @@ -25,20 +25,9 @@ public static ModelMetadata GetMetadataForProperty( Type containerType, string propertyName) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (containerType == null) - { - throw new ArgumentNullException(nameof(containerType)); - } - - if (propertyName == null) - { - throw new ArgumentNullException(nameof(propertyName)); - } + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(containerType); + ArgumentNullException.ThrowIfNull(propertyName); var containerMetadata = provider.GetMetadataForType(containerType); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ObjectModelValidator.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ObjectModelValidator.cs index b79752308ae7..4cc341d861cc 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ObjectModelValidator.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ObjectModelValidator.cs @@ -25,15 +25,8 @@ public ObjectModelValidator( IModelMetadataProvider modelMetadataProvider, IList validatorProviders) { - if (modelMetadataProvider == null) - { - throw new ArgumentNullException(nameof(modelMetadataProvider)); - } - - if (validatorProviders == null) - { - throw new ArgumentNullException(nameof(validatorProviders)); - } + ArgumentNullException.ThrowIfNull(modelMetadataProvider); + ArgumentNullException.ThrowIfNull(validatorProviders); _modelMetadataProvider = modelMetadataProvider; _validatorCache = new ValidatorCache(); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ParameterBinder.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ParameterBinder.cs index 54386437510f..e6e66166bbed 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ParameterBinder.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ParameterBinder.cs @@ -34,30 +34,11 @@ public ParameterBinder( IOptions mvcOptions, ILoggerFactory loggerFactory) { - if (modelMetadataProvider == null) - { - throw new ArgumentNullException(nameof(modelMetadataProvider)); - } - - if (modelBinderFactory == null) - { - throw new ArgumentNullException(nameof(modelBinderFactory)); - } - - if (validator == null) - { - throw new ArgumentNullException(nameof(validator)); - } - - if (mvcOptions == null) - { - throw new ArgumentNullException(nameof(mvcOptions)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(modelMetadataProvider); + ArgumentNullException.ThrowIfNull(modelBinderFactory); + ArgumentNullException.ThrowIfNull(validator); + ArgumentNullException.ThrowIfNull(mvcOptions); + ArgumentNullException.ThrowIfNull(loggerFactory); _modelMetadataProvider = modelMetadataProvider; _modelBinderFactory = modelBinderFactory; @@ -109,30 +90,11 @@ public virtual async ValueTask BindModelAsync( object? value, object? container) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (modelBinder == null) - { - throw new ArgumentNullException(nameof(modelBinder)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(modelBinder); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(parameter); + ArgumentNullException.ThrowIfNull(metadata); Log.AttemptingToBindParameterOrProperty(Logger, parameter, metadata); diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs b/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs index fa7ddc8c2060..aeab151eb80f 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/PrefixContainer.cs @@ -23,10 +23,7 @@ public class PrefixContainer /// The values for the container. public PrefixContainer(ICollection values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); _originalValues = values; @@ -49,10 +46,7 @@ public PrefixContainer(ICollection values) /// True if the prefix is present. public bool ContainsPrefix(string prefix) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(prefix); if (_sortedValues.Length == 0) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProvider.cs index ff3105380c1c..a1af0aaa9970 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProvider.cs @@ -28,15 +28,8 @@ public QueryStringValueProvider( CultureInfo? culture) : base(bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(bindingSource); + ArgumentNullException.ThrowIfNull(values); _values = values; Culture = culture; @@ -72,10 +65,7 @@ public override bool ContainsPrefix(string prefix) /// public virtual IDictionary GetKeysFromPrefix(string prefix) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(prefix); return PrefixContainer.GetKeysFromPrefix(prefix); } @@ -83,10 +73,7 @@ public virtual IDictionary GetKeysFromPrefix(string prefix) /// public override ValueProviderResult GetValue(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (key.Length == 0) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProviderFactory.cs index 326716ae089a..89039f5bdd94 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/QueryStringValueProviderFactory.cs @@ -16,10 +16,7 @@ public class QueryStringValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var query = context.ActionContext.HttpContext.Request.Query; if (query != null && query.Count > 0) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProvider.cs index dc1094ec2c4d..128ae5fbdc81 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProvider.cs @@ -38,20 +38,9 @@ public RouteValueProvider( public RouteValueProvider(BindingSource bindingSource, RouteValueDictionary values, CultureInfo culture) : base(bindingSource) { - if (bindingSource == null) - { - throw new ArgumentNullException(nameof(bindingSource)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } + ArgumentNullException.ThrowIfNull(bindingSource); + ArgumentNullException.ThrowIfNull(values); + ArgumentNullException.ThrowIfNull(culture); _values = values; Culture = culture; @@ -87,10 +76,7 @@ public override bool ContainsPrefix(string key) /// public override ValueProviderResult GetValue(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (key.Length == 0) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProviderFactory.cs b/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProviderFactory.cs index 0fc009d6cf34..e3ba2f7f76ac 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProviderFactory.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/RouteValueProviderFactory.cs @@ -13,10 +13,7 @@ public class RouteValueProviderFactory : IValueProviderFactory /// public Task CreateValueProviderAsync(ValueProviderFactoryContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var valueProvider = new RouteValueProvider( BindingSource.Path, diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/SuppressChildValidationMetadataProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/SuppressChildValidationMetadataProvider.cs index 2bc2a38c7e7a..b47367c99b95 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/SuppressChildValidationMetadataProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/SuppressChildValidationMetadataProvider.cs @@ -23,10 +23,7 @@ public class SuppressChildValidationMetadataProvider : IValidationMetadataProvid /// public SuppressChildValidationMetadataProvider(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); Type = type; } @@ -40,10 +37,7 @@ public SuppressChildValidationMetadataProvider(Type type) /// public SuppressChildValidationMetadataProvider(string fullTypeName) { - if (fullTypeName == null) - { - throw new ArgumentNullException(nameof(fullTypeName)); - } + ArgumentNullException.ThrowIfNull(fullTypeName); FullTypeName = fullTypeName; } @@ -61,10 +55,7 @@ public SuppressChildValidationMetadataProvider(string fullTypeName) /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (Type != null) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeClientModelValidatorProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeClientModelValidatorProvider.cs index 100068396087..fd4ca07997d8 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeClientModelValidatorProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeClientModelValidatorProvider.cs @@ -18,10 +18,7 @@ public class CompositeClientModelValidatorProvider : IClientModelValidatorProvid /// public CompositeClientModelValidatorProvider(IEnumerable providers) { - if (providers == null) - { - throw new ArgumentNullException(nameof(providers)); - } + ArgumentNullException.ThrowIfNull(providers); ValidatorProviders = new List(providers); } @@ -34,10 +31,7 @@ public CompositeClientModelValidatorProvider(IEnumerable public void CreateValidators(ClientValidatorProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Perf: Avoid allocations for (var i = 0; i < ValidatorProviders.Count; i++) diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeModelValidatorProvider.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeModelValidatorProvider.cs index af09a0083a60..b8334855e07e 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeModelValidatorProvider.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/CompositeModelValidatorProvider.cs @@ -18,10 +18,7 @@ public class CompositeModelValidatorProvider : IModelValidatorProvider /// public CompositeModelValidatorProvider(IList providers) { - if (providers == null) - { - throw new ArgumentNullException(nameof(providers)); - } + ArgumentNullException.ThrowIfNull(providers); ValidatorProviders = providers; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ExplicitIndexCollectionValidationStrategy.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ExplicitIndexCollectionValidationStrategy.cs index 908cebfda202..f504ffc72053 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ExplicitIndexCollectionValidationStrategy.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ExplicitIndexCollectionValidationStrategy.cs @@ -35,10 +35,7 @@ internal sealed class ExplicitIndexCollectionValidationStrategy : IValidationStr /// The keys of collection elements that were used during model binding. public ExplicitIndexCollectionValidationStrategy(IEnumerable elementKeys) { - if (elementKeys == null) - { - throw new ArgumentNullException(nameof(elementKeys)); - } + ArgumentNullException.ThrowIfNull(elementKeys); ElementKeys = elementKeys; } diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ModelValidatorProviderExtensions.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ModelValidatorProviderExtensions.cs index 8683600cb721..b73171f49c43 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ModelValidatorProviderExtensions.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ModelValidatorProviderExtensions.cs @@ -17,10 +17,7 @@ public static class ModelValidatorProviderExtensions /// The type to remove. public static void RemoveType(this IList list) where TModelValidatorProvider : IModelValidatorProvider { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); RemoveType(list, typeof(TModelValidatorProvider)); } @@ -32,15 +29,8 @@ public static void RemoveType(this IListThe type to remove. public static void RemoveType(this IList list, Type type) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(type); for (var i = list.Count - 1; i >= 0; i--) { diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ValidationVisitor.cs b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ValidationVisitor.cs index 2f68aa6a26fd..68c71a5e4807 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ValidationVisitor.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/Validation/ValidationVisitor.cs @@ -34,20 +34,9 @@ public ValidationVisitor( IModelMetadataProvider metadataProvider, ValidationStateDictionary? validationState) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (validatorProvider == null) - { - throw new ArgumentNullException(nameof(validatorProvider)); - } - - if (validatorCache == null) - { - throw new ArgumentNullException(nameof(validatorCache)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(validatorProvider); + ArgumentNullException.ThrowIfNull(validatorCache); Context = actionContext; ValidatorProvider = validatorProvider; diff --git a/src/Mvc/Mvc.Core/src/ModelBinding/ValueProviderFactoryExtensions.cs b/src/Mvc/Mvc.Core/src/ModelBinding/ValueProviderFactoryExtensions.cs index 36eaa36e4655..4d68186d500d 100644 --- a/src/Mvc/Mvc.Core/src/ModelBinding/ValueProviderFactoryExtensions.cs +++ b/src/Mvc/Mvc.Core/src/ModelBinding/ValueProviderFactoryExtensions.cs @@ -17,10 +17,7 @@ public static class ValueProviderFactoryExtensions /// The type to remove. public static void RemoveType(this IList list) where TValueProviderFactory : IValueProviderFactory { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } + ArgumentNullException.ThrowIfNull(list); RemoveType(list, typeof(TValueProviderFactory)); } @@ -32,15 +29,8 @@ public static void RemoveType(this IListThe type to remove. public static void RemoveType(this IList list, Type type) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(type); for (var i = list.Count - 1; i >= 0; i--) { diff --git a/src/Mvc/Mvc.Core/src/ModelMetadataTypeAttribute.cs b/src/Mvc/Mvc.Core/src/ModelMetadataTypeAttribute.cs index f50f4a52e98a..2bd556183de2 100644 --- a/src/Mvc/Mvc.Core/src/ModelMetadataTypeAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ModelMetadataTypeAttribute.cs @@ -15,10 +15,7 @@ public class ModelMetadataTypeAttribute : Attribute /// The type of metadata class that is associated with a data model class. public ModelMetadataTypeAttribute(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); MetadataType = type; } diff --git a/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs b/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs index dc067944f283..e8052e8b8dc1 100644 --- a/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs +++ b/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs @@ -283,10 +283,7 @@ private sealed class ActionLogScope : IReadOnlyList public ActionLogScope(ActionDescriptor action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); _action = action; } diff --git a/src/Mvc/Mvc.Core/src/MvcOptions.cs b/src/Mvc/Mvc.Core/src/MvcOptions.cs index 7a59a9834738..676aae1a30b8 100644 --- a/src/Mvc/Mvc.Core/src/MvcOptions.cs +++ b/src/Mvc/Mvc.Core/src/MvcOptions.cs @@ -153,10 +153,7 @@ public int MaxModelValidationErrors get => _maxModelStateErrors; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _maxModelStateErrors = value; } @@ -318,10 +315,7 @@ public int MaxModelBindingCollectionSize set { // Disallowing an empty collection would cause the CollectionModelBinder to throw unconditionally. - if (value <= 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); _maxModelBindingCollectionSize = value; } @@ -357,10 +351,7 @@ public int MaxModelBindingRecursionDepth { // Disallowing one model binder (if supported) would cause the model binding system to throw // unconditionally. DefaultModelBindingContext always allows a top-level binder i.e. its own creation. - if (value <= 1) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(value, 1); _maxModelBindingRecursionDepth = value; } diff --git a/src/Mvc/Mvc.Core/src/ObjectResult.cs b/src/Mvc/Mvc.Core/src/ObjectResult.cs index 278b8211fb5c..c94b5c831976 100644 --- a/src/Mvc/Mvc.Core/src/ObjectResult.cs +++ b/src/Mvc/Mvc.Core/src/ObjectResult.cs @@ -68,10 +68,7 @@ public override Task ExecuteResultAsync(ActionContext context) /// public virtual void OnFormatting(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (Value is ProblemDetails details) { diff --git a/src/Mvc/Mvc.Core/src/PhysicalFileResult.cs b/src/Mvc/Mvc.Core/src/PhysicalFileResult.cs index 8fe502106c50..c003cdb8f4d3 100644 --- a/src/Mvc/Mvc.Core/src/PhysicalFileResult.cs +++ b/src/Mvc/Mvc.Core/src/PhysicalFileResult.cs @@ -25,10 +25,7 @@ public class PhysicalFileResult : FileResult public PhysicalFileResult(string fileName, string contentType) : this(fileName, MediaTypeHeaderValue.Parse(contentType)) { - if (fileName == null) - { - throw new ArgumentNullException(nameof(fileName)); - } + ArgumentNullException.ThrowIfNull(fileName); } /// @@ -56,10 +53,7 @@ public string FileName /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/ProducesAttribute.cs b/src/Mvc/Mvc.Core/src/ProducesAttribute.cs index 3223300c7a81..f7bbbc380dfc 100644 --- a/src/Mvc/Mvc.Core/src/ProducesAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ProducesAttribute.cs @@ -35,10 +35,7 @@ public ProducesAttribute(Type type) /// Additional allowed content types for a response. public ProducesAttribute(string contentType, params string[] additionalContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); // We want to ensure that the given provided content types are valid values, so // we validate them using the semantics of MediaTypeHeaderValue. @@ -69,10 +66,7 @@ public ProducesAttribute(string contentType, params string[] additionalContentTy /// public virtual void OnResultExecuting(ResultExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Result is ObjectResult objectResult) { diff --git a/src/Mvc/Mvc.Core/src/ProducesResponseTypeAttribute.cs b/src/Mvc/Mvc.Core/src/ProducesResponseTypeAttribute.cs index e04a7bf152e4..6399a66d464d 100644 --- a/src/Mvc/Mvc.Core/src/ProducesResponseTypeAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ProducesResponseTypeAttribute.cs @@ -47,10 +47,7 @@ public ProducesResponseTypeAttribute(Type type, int statusCode) /// Additional content types supported by the response. public ProducesResponseTypeAttribute(Type type, int statusCode, string contentType, params string[] additionalContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); Type = type ?? throw new ArgumentNullException(nameof(type)); StatusCode = statusCode; diff --git a/src/Mvc/Mvc.Core/src/RedirectResult.cs b/src/Mvc/Mvc.Core/src/RedirectResult.cs index e56c1dc5d286..9c0d16271f8b 100644 --- a/src/Mvc/Mvc.Core/src/RedirectResult.cs +++ b/src/Mvc/Mvc.Core/src/RedirectResult.cs @@ -25,10 +25,7 @@ public class RedirectResult : ActionResult, IKeepTempDataResult public RedirectResult([StringSyntax(StringSyntaxAttribute.Uri)] string url) : this(url, permanent: false) { - if (url == null) - { - throw new ArgumentNullException(nameof(url)); - } + ArgumentNullException.ThrowIfNull(url); } /// @@ -51,10 +48,7 @@ public RedirectResult([StringSyntax(StringSyntaxAttribute.Uri)] string url, bool /// If set to true, make the temporary redirect (307) or permanent redirect (308) preserve the initial request method. public RedirectResult([StringSyntax(StringSyntaxAttribute.Uri)] string url, bool permanent, bool preserveMethod) { - if (url == null) - { - throw new ArgumentNullException(nameof(url)); - } + ArgumentNullException.ThrowIfNull(url); if (string.IsNullOrEmpty(url)) { @@ -102,10 +96,7 @@ public string Url /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/RedirectToActionResult.cs b/src/Mvc/Mvc.Core/src/RedirectToActionResult.cs index 6487e4de3b08..6941340d5333 100644 --- a/src/Mvc/Mvc.Core/src/RedirectToActionResult.cs +++ b/src/Mvc/Mvc.Core/src/RedirectToActionResult.cs @@ -166,10 +166,7 @@ public RedirectToActionResult( /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/RedirectToPageResult.cs b/src/Mvc/Mvc.Core/src/RedirectToPageResult.cs index 4bd1433b23b2..67b3cb27598e 100644 --- a/src/Mvc/Mvc.Core/src/RedirectToPageResult.cs +++ b/src/Mvc/Mvc.Core/src/RedirectToPageResult.cs @@ -204,10 +204,7 @@ public RedirectToPageResult( /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/RedirectToRouteResult.cs b/src/Mvc/Mvc.Core/src/RedirectToRouteResult.cs index 6475ff79e3c1..021d5ae0316f 100644 --- a/src/Mvc/Mvc.Core/src/RedirectToRouteResult.cs +++ b/src/Mvc/Mvc.Core/src/RedirectToRouteResult.cs @@ -158,10 +158,7 @@ public RedirectToRouteResult( /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/src/RequireHttpsAttribute.cs b/src/Mvc/Mvc.Core/src/RequireHttpsAttribute.cs index 8ca8588abc83..fbc0d9f3c1b5 100644 --- a/src/Mvc/Mvc.Core/src/RequireHttpsAttribute.cs +++ b/src/Mvc/Mvc.Core/src/RequireHttpsAttribute.cs @@ -40,10 +40,7 @@ public bool Permanent /// public virtual void OnAuthorization(AuthorizationFilterContext filterContext) { - if (filterContext == null) - { - throw new ArgumentNullException(nameof(filterContext)); - } + ArgumentNullException.ThrowIfNull(filterContext); if (!filterContext.HttpContext.Request.IsHttps) { diff --git a/src/Mvc/Mvc.Core/src/ResponseCacheAttribute.cs b/src/Mvc/Mvc.Core/src/ResponseCacheAttribute.cs index adbb03978b66..f00d6581e66e 100644 --- a/src/Mvc/Mvc.Core/src/ResponseCacheAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ResponseCacheAttribute.cs @@ -117,10 +117,7 @@ public CacheProfile GetCacheProfile(MvcOptions options) /// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); var loggerFactory = serviceProvider.GetRequiredService(); var optionsAccessor = serviceProvider.GetRequiredService>(); diff --git a/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs b/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs index 149bcfe271c8..8383b317291a 100644 --- a/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs +++ b/src/Mvc/Mvc.Core/src/Routing/ActionConstraintMatcherPolicy.cs @@ -30,10 +30,7 @@ public ActionConstraintMatcherPolicy(ActionConstraintCache actionConstraintCache public bool AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // We can skip over action constraints when they aren't any for this set // of endpoints. This happens once on startup so it removes this component diff --git a/src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs b/src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs index c16bf8040d76..a51ed5e2b699 100644 --- a/src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs +++ b/src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs @@ -27,10 +27,7 @@ public ActionEndpointFactory(RoutePatternTransformer routePatternTransformer, IEnumerable requestDelegateFactories, IServiceProvider serviceProvider) { - if (routePatternTransformer == null) - { - throw new ArgumentNullException(nameof(routePatternTransformer)); - } + ArgumentNullException.ThrowIfNull(routePatternTransformer); _routePatternTransformer = routePatternTransformer; _requestDelegate = CreateRequestDelegate(); @@ -185,20 +182,9 @@ public void AddConventionalLinkGenerationRoute( IReadOnlyList> finallyConventions, RoutePattern? groupPrefix = null) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (keys == null) - { - throw new ArgumentNullException(nameof(keys)); - } - - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(keys); + ArgumentNullException.ThrowIfNull(conventions); var requiredValues = new RouteValueDictionary(); foreach (var key in keys) diff --git a/src/Mvc/Mvc.Core/src/Routing/AttributeRoute.cs b/src/Mvc/Mvc.Core/src/Routing/AttributeRoute.cs index 4bfa31e7ec86..e62b37a22271 100644 --- a/src/Mvc/Mvc.Core/src/Routing/AttributeRoute.cs +++ b/src/Mvc/Mvc.Core/src/Routing/AttributeRoute.cs @@ -25,20 +25,9 @@ public AttributeRoute( IServiceProvider services, Func handlerFactory) { - if (actionDescriptorCollectionProvider == null) - { - throw new ArgumentNullException(nameof(actionDescriptorCollectionProvider)); - } - - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (handlerFactory == null) - { - throw new ArgumentNullException(nameof(handlerFactory)); - } + ArgumentNullException.ThrowIfNull(actionDescriptorCollectionProvider); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(handlerFactory); _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; _services = services; diff --git a/src/Mvc/Mvc.Core/src/Routing/AttributeRouting.cs b/src/Mvc/Mvc.Core/src/Routing/AttributeRouting.cs index bc55f0b9b787..c5df314076c5 100644 --- a/src/Mvc/Mvc.Core/src/Routing/AttributeRouting.cs +++ b/src/Mvc/Mvc.Core/src/Routing/AttributeRouting.cs @@ -16,10 +16,7 @@ internal static class AttributeRouting /// An attribute route. public static IRouter CreateAttributeMegaRoute(IServiceProvider services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); return new AttributeRoute( services.GetRequiredService(), diff --git a/src/Mvc/Mvc.Core/src/Routing/ControllerLinkGeneratorExtensions.cs b/src/Mvc/Mvc.Core/src/Routing/ControllerLinkGeneratorExtensions.cs index a6196cd7abd1..fc39b06a6aa3 100644 --- a/src/Mvc/Mvc.Core/src/Routing/ControllerLinkGeneratorExtensions.cs +++ b/src/Mvc/Mvc.Core/src/Routing/ControllerLinkGeneratorExtensions.cs @@ -47,15 +47,8 @@ public static class ControllerLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, action, controller, values); return generator.GetPathByAddress( @@ -92,20 +85,9 @@ public static class ControllerLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); var address = CreateAddress(httpContext: null, action, controller, values); return generator.GetPathByAddress(address, address.ExplicitValues, pathBase, fragment, options); @@ -161,15 +143,8 @@ public static class ControllerLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, action, controller, values); return generator.GetUriByAddress( @@ -220,20 +195,9 @@ public static class ControllerLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - if (controller == null) - { - throw new ArgumentNullException(nameof(controller)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(action); + ArgumentNullException.ThrowIfNull(controller); var address = CreateAddress(httpContext: null, action, controller, values); return generator.GetUriByAddress(address, address.ExplicitValues, scheme, host, pathBase, fragment, options); diff --git a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointMatcherPolicy.cs b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointMatcherPolicy.cs index 87ba4bdd237c..50e13bee15a3 100644 --- a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointMatcherPolicy.cs +++ b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointMatcherPolicy.cs @@ -18,15 +18,8 @@ internal sealed class DynamicControllerEndpointMatcherPolicy : MatcherPolicy, IE public DynamicControllerEndpointMatcherPolicy(DynamicControllerEndpointSelectorCache selectorCache, EndpointMetadataComparer comparer) { - if (selectorCache == null) - { - throw new ArgumentNullException(nameof(selectorCache)); - } - - if (comparer == null) - { - throw new ArgumentNullException(nameof(comparer)); - } + ArgumentNullException.ThrowIfNull(selectorCache); + ArgumentNullException.ThrowIfNull(comparer); _selectorCache = selectorCache; _comparer = comparer; @@ -36,10 +29,7 @@ public DynamicControllerEndpointMatcherPolicy(DynamicControllerEndpointSelectorC public bool AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); if (!ContainsDynamicEndpoints(endpoints)) { @@ -67,15 +57,8 @@ public bool AppliesToEndpoints(IReadOnlyList endpoints) public async Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); // The per-route selector, must be the same for all the endpoints we are dealing with. DynamicControllerEndpointSelector? selector = null; diff --git a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelector.cs b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelector.cs index 1d041461ffaf..97ecd7bf3579 100644 --- a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelector.cs +++ b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerEndpointSelector.cs @@ -13,10 +13,7 @@ internal sealed class DynamicControllerEndpointSelector : IDisposable public DynamicControllerEndpointSelector(EndpointDataSource dataSource) { - if (dataSource == null) - { - throw new ArgumentNullException(nameof(dataSource)); - } + ArgumentNullException.ThrowIfNull(dataSource); _cache = new DataSourceDependentCache>(dataSource, Initialize); } @@ -25,10 +22,7 @@ public DynamicControllerEndpointSelector(EndpointDataSource dataSource) public IReadOnlyList SelectEndpoints(RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); var table = Table; var matches = table.Select(values); diff --git a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerMetadata.cs b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerMetadata.cs index a37fb08aaa6a..90b6d3d07e62 100644 --- a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerMetadata.cs +++ b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerMetadata.cs @@ -9,10 +9,7 @@ internal sealed class DynamicControllerMetadata : IDynamicEndpointMetadata { public DynamicControllerMetadata(RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); Values = values; } diff --git a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerRouteValueTransformerMetadata.cs b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerRouteValueTransformerMetadata.cs index bbe072da7907..5424c3706bbd 100644 --- a/src/Mvc/Mvc.Core/src/Routing/DynamicControllerRouteValueTransformerMetadata.cs +++ b/src/Mvc/Mvc.Core/src/Routing/DynamicControllerRouteValueTransformerMetadata.cs @@ -9,10 +9,7 @@ internal sealed class DynamicControllerRouteValueTransformerMetadata : IDynamicE { public DynamicControllerRouteValueTransformerMetadata(Type selectorType, object? state) { - if (selectorType == null) - { - throw new ArgumentNullException(nameof(selectorType)); - } + ArgumentNullException.ThrowIfNull(selectorType); if (!typeof(DynamicRouteValueTransformer).IsAssignableFrom(selectorType)) { diff --git a/src/Mvc/Mvc.Core/src/Routing/EndpointRoutingUrlHelper.cs b/src/Mvc/Mvc.Core/src/Routing/EndpointRoutingUrlHelper.cs index 1546cf167ef5..7b18d68b1884 100644 --- a/src/Mvc/Mvc.Core/src/Routing/EndpointRoutingUrlHelper.cs +++ b/src/Mvc/Mvc.Core/src/Routing/EndpointRoutingUrlHelper.cs @@ -29,15 +29,8 @@ public EndpointRoutingUrlHelper( ILogger logger) : base(actionContext) { - if (linkGenerator == null) - { - throw new ArgumentNullException(nameof(linkGenerator)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(linkGenerator); + ArgumentNullException.ThrowIfNull(logger); _linkGenerator = linkGenerator; _logger = logger; @@ -46,10 +39,7 @@ public EndpointRoutingUrlHelper( /// public override string? Action(UrlActionContext urlActionContext) { - if (urlActionContext == null) - { - throw new ArgumentNullException(nameof(urlActionContext)); - } + ArgumentNullException.ThrowIfNull(urlActionContext); var values = GetValuesDictionary(urlActionContext.Values); @@ -90,10 +80,7 @@ public EndpointRoutingUrlHelper( /// public override string? RouteUrl(UrlRouteContext routeContext) { - if (routeContext == null) - { - throw new ArgumentNullException(nameof(routeContext)); - } + ArgumentNullException.ThrowIfNull(routeContext); var path = _linkGenerator.GetPathByRouteValues( ActionContext.HttpContext, diff --git a/src/Mvc/Mvc.Core/src/Routing/HttpMethodAttribute.cs b/src/Mvc/Mvc.Core/src/Routing/HttpMethodAttribute.cs index 8da7644822e8..8aad64e145ca 100644 --- a/src/Mvc/Mvc.Core/src/Routing/HttpMethodAttribute.cs +++ b/src/Mvc/Mvc.Core/src/Routing/HttpMethodAttribute.cs @@ -34,10 +34,7 @@ public HttpMethodAttribute(IEnumerable httpMethods) /// The route template. public HttpMethodAttribute(IEnumerable httpMethods, [StringSyntax("Route")] string? template) { - if (httpMethods == null) - { - throw new ArgumentNullException(nameof(httpMethods)); - } + ArgumentNullException.ThrowIfNull(httpMethods); _httpMethods = httpMethods.ToList(); Template = template; diff --git a/src/Mvc/Mvc.Core/src/Routing/KnownRouteValueConstraint.cs b/src/Mvc/Mvc.Core/src/Routing/KnownRouteValueConstraint.cs index 5bcb3dbd2a9a..6839f9c8c212 100644 --- a/src/Mvc/Mvc.Core/src/Routing/KnownRouteValueConstraint.cs +++ b/src/Mvc/Mvc.Core/src/Routing/KnownRouteValueConstraint.cs @@ -25,10 +25,7 @@ public class KnownRouteValueConstraint : IRouteConstraint /// The . public KnownRouteValueConstraint(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { - if (actionDescriptorCollectionProvider == null) - { - throw new ArgumentNullException(nameof(actionDescriptorCollectionProvider)); - } + ArgumentNullException.ThrowIfNull(actionDescriptorCollectionProvider); _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } @@ -41,15 +38,8 @@ public bool Match( RouteValueDictionary values, RouteDirection routeDirection) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(values); if (values.TryGetValue(routeKey, out var obj)) { @@ -79,10 +69,7 @@ private ActionDescriptorCollection GetAndValidateActionDescriptors(HttpContext? if (actionDescriptorsProvider == null) { // Only validate that HttpContext was passed to constraint if it is needed - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(httpContext); var services = httpContext.RequestServices; actionDescriptorsProvider = services.GetRequiredService(); diff --git a/src/Mvc/Mvc.Core/src/Routing/MvcAttributeRouteHandler.cs b/src/Mvc/Mvc.Core/src/Routing/MvcAttributeRouteHandler.cs index 9c788cef2da7..c9143aa79778 100644 --- a/src/Mvc/Mvc.Core/src/Routing/MvcAttributeRouteHandler.cs +++ b/src/Mvc/Mvc.Core/src/Routing/MvcAttributeRouteHandler.cs @@ -33,10 +33,7 @@ public MvcAttributeRouteHandler( public VirtualPathData? GetVirtualPath(VirtualPathContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // We return null here because we're not responsible for generating the url, the route is. return null; @@ -44,10 +41,7 @@ public MvcAttributeRouteHandler( public Task RouteAsync(RouteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (Actions == null) { diff --git a/src/Mvc/Mvc.Core/src/Routing/MvcRouteHandler.cs b/src/Mvc/Mvc.Core/src/Routing/MvcRouteHandler.cs index b2cecc9a54c1..c9b6549e18ba 100644 --- a/src/Mvc/Mvc.Core/src/Routing/MvcRouteHandler.cs +++ b/src/Mvc/Mvc.Core/src/Routing/MvcRouteHandler.cs @@ -30,10 +30,7 @@ public MvcRouteHandler( public VirtualPathData? GetVirtualPath(VirtualPathContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // We return null here because we're not responsible for generating the url, the route is. return null; @@ -41,10 +38,7 @@ public MvcRouteHandler( public Task RouteAsync(RouteContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var candidates = _actionSelector.SelectCandidates(context); if (candidates == null || candidates.Count == 0) diff --git a/src/Mvc/Mvc.Core/src/Routing/NormalizedRouteValue.cs b/src/Mvc/Mvc.Core/src/Routing/NormalizedRouteValue.cs index ca101e4b1053..32eb2e84fb97 100644 --- a/src/Mvc/Mvc.Core/src/Routing/NormalizedRouteValue.cs +++ b/src/Mvc/Mvc.Core/src/Routing/NormalizedRouteValue.cs @@ -21,15 +21,8 @@ internal static class NormalizedRouteValue /// public static string? GetNormalizedRouteValue(ActionContext context, string key) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(key); if (!context.RouteData.Values.TryGetValue(key, out var routeValue)) { diff --git a/src/Mvc/Mvc.Core/src/Routing/PageLinkGeneratorExtensions.cs b/src/Mvc/Mvc.Core/src/Routing/PageLinkGeneratorExtensions.cs index 51d6c0fa0ba1..02b4a675610f 100644 --- a/src/Mvc/Mvc.Core/src/Routing/PageLinkGeneratorExtensions.cs +++ b/src/Mvc/Mvc.Core/src/Routing/PageLinkGeneratorExtensions.cs @@ -46,15 +46,8 @@ public static class PageLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, page, handler, values); return generator.GetPathByAddress( @@ -95,15 +88,8 @@ public static class PageLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(page); var address = CreateAddress(httpContext: null, page, handler, values); return generator.GetPathByAddress(address, address.ExplicitValues, pathBase, fragment, options); @@ -158,15 +144,8 @@ public static class PageLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(httpContext); var address = CreateAddress(httpContext, page, handler, values); return generator.GetUriByAddress( @@ -217,15 +196,8 @@ public static class PageLinkGeneratorExtensions FragmentString fragment = default, LinkOptions? options = default) { - if (generator == null) - { - throw new ArgumentNullException(nameof(generator)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(generator); + ArgumentNullException.ThrowIfNull(page); var address = CreateAddress(httpContext: null, page, handler, values); return generator.GetUriByAddress(address, address.ExplicitValues, scheme, host, pathBase, fragment, options); diff --git a/src/Mvc/Mvc.Core/src/Routing/RouteValueAttribute.cs b/src/Mvc/Mvc.Core/src/Routing/RouteValueAttribute.cs index 8f8db414c0ae..d592c73a53a6 100644 --- a/src/Mvc/Mvc.Core/src/Routing/RouteValueAttribute.cs +++ b/src/Mvc/Mvc.Core/src/Routing/RouteValueAttribute.cs @@ -30,15 +30,8 @@ protected RouteValueAttribute( string routeKey, string routeValue) { - if (routeKey == null) - { - throw new ArgumentNullException(nameof(routeKey)); - } - - if (routeValue == null) - { - throw new ArgumentNullException(nameof(routeValue)); - } + ArgumentNullException.ThrowIfNull(routeKey); + ArgumentNullException.ThrowIfNull(routeValue); RouteKey = routeKey; RouteValue = routeValue; diff --git a/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs b/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs index deaa3260b78a..1a9266c79147 100644 --- a/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs +++ b/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs @@ -50,10 +50,7 @@ protected IRouter Router /// public override string? Action(UrlActionContext actionContext) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } + ArgumentNullException.ThrowIfNull(actionContext); var valuesDictionary = GetValuesDictionary(actionContext.Values); @@ -66,10 +63,7 @@ protected IRouter Router /// public override string? RouteUrl(UrlRouteContext routeContext) { - if (routeContext == null) - { - throw new ArgumentNullException(nameof(routeContext)); - } + ArgumentNullException.ThrowIfNull(routeContext); var valuesDictionary = routeContext.Values as RouteValueDictionary ?? GetValuesDictionary(routeContext.Values); var virtualPathData = GetVirtualPathData(routeContext.RouteName, valuesDictionary); diff --git a/src/Mvc/Mvc.Core/src/Routing/UrlHelperBase.cs b/src/Mvc/Mvc.Core/src/Routing/UrlHelperBase.cs index f3ec6f6a1edd..2b0fa0b1a8f2 100644 --- a/src/Mvc/Mvc.Core/src/Routing/UrlHelperBase.cs +++ b/src/Mvc/Mvc.Core/src/Routing/UrlHelperBase.cs @@ -28,10 +28,7 @@ public abstract class UrlHelperBase : IUrlHelper /// The . protected UrlHelperBase(ActionContext actionContext) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } + ArgumentNullException.ThrowIfNull(actionContext); ActionContext = actionContext; AmbientValues = actionContext.RouteData.Values; diff --git a/src/Mvc/Mvc.Core/src/Routing/UrlHelperFactory.cs b/src/Mvc/Mvc.Core/src/Routing/UrlHelperFactory.cs index 5d13633368bc..b3346a9b9836 100644 --- a/src/Mvc/Mvc.Core/src/Routing/UrlHelperFactory.cs +++ b/src/Mvc/Mvc.Core/src/Routing/UrlHelperFactory.cs @@ -17,10 +17,7 @@ public class UrlHelperFactory : IUrlHelperFactory /// public IUrlHelper GetUrlHelper(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var httpContext = context.HttpContext; diff --git a/src/Mvc/Mvc.Core/src/SerializableError.cs b/src/Mvc/Mvc.Core/src/SerializableError.cs index 12e6984bb99a..bc7d62e17b9f 100644 --- a/src/Mvc/Mvc.Core/src/SerializableError.cs +++ b/src/Mvc/Mvc.Core/src/SerializableError.cs @@ -28,10 +28,7 @@ public SerializableError() public SerializableError(ModelStateDictionary modelState) : this() { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); if (modelState.IsValid) { diff --git a/src/Mvc/Mvc.Core/src/ServiceFilterAttribute.cs b/src/Mvc/Mvc.Core/src/ServiceFilterAttribute.cs index ae259d7f1581..af736666dab3 100644 --- a/src/Mvc/Mvc.Core/src/ServiceFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/ServiceFilterAttribute.cs @@ -46,10 +46,7 @@ public ServiceFilterAttribute(Type type) /// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); var filter = (IFilterMetadata)serviceProvider.GetRequiredService(ServiceType); if (filter is IFilterFactory filterFactory) diff --git a/src/Mvc/Mvc.Core/src/SignInResult.cs b/src/Mvc/Mvc.Core/src/SignInResult.cs index 05129a07fe26..974b8b5ba65d 100644 --- a/src/Mvc/Mvc.Core/src/SignInResult.cs +++ b/src/Mvc/Mvc.Core/src/SignInResult.cs @@ -77,10 +77,7 @@ public SignInResult(string? authenticationScheme, ClaimsPrincipal principal, Aut /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var httpContext = context.HttpContext; var loggerFactory = httpContext.RequestServices.GetRequiredService(); diff --git a/src/Mvc/Mvc.Core/src/SignOutResult.cs b/src/Mvc/Mvc.Core/src/SignOutResult.cs index adb914173c5d..de12f9f14f07 100644 --- a/src/Mvc/Mvc.Core/src/SignOutResult.cs +++ b/src/Mvc/Mvc.Core/src/SignOutResult.cs @@ -89,10 +89,7 @@ public SignOutResult(IList authenticationSchemes, AuthenticationProperti /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return ExecuteAsync(context.HttpContext); } diff --git a/src/Mvc/Mvc.Core/src/StatusCodeResult.cs b/src/Mvc/Mvc.Core/src/StatusCodeResult.cs index bd465c718286..42a9a5f39745 100644 --- a/src/Mvc/Mvc.Core/src/StatusCodeResult.cs +++ b/src/Mvc/Mvc.Core/src/StatusCodeResult.cs @@ -33,10 +33,7 @@ public StatusCodeResult([ActionResultStatusCode] int statusCode) /// public override void ExecuteResult(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var httpContext = context.HttpContext; var factory = httpContext.RequestServices.GetRequiredService(); diff --git a/src/Mvc/Mvc.Core/src/TypeFilterAttribute.cs b/src/Mvc/Mvc.Core/src/TypeFilterAttribute.cs index 045fe41c04eb..0b3c87bbdc80 100644 --- a/src/Mvc/Mvc.Core/src/TypeFilterAttribute.cs +++ b/src/Mvc/Mvc.Core/src/TypeFilterAttribute.cs @@ -59,10 +59,7 @@ public TypeFilterAttribute(Type type) /// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); if (_factory == null) { diff --git a/src/Mvc/Mvc.Core/src/UrlHelperExtensions.cs b/src/Mvc/Mvc.Core/src/UrlHelperExtensions.cs index 7d55504cb830..baf839fb16c2 100644 --- a/src/Mvc/Mvc.Core/src/UrlHelperExtensions.cs +++ b/src/Mvc/Mvc.Core/src/UrlHelperExtensions.cs @@ -19,10 +19,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? Action(this IUrlHelper helper) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action( action: null, @@ -42,10 +39,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? Action(this IUrlHelper helper, string? action) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller: null, values: null, protocol: null, host: null, fragment: null); } @@ -60,10 +54,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? Action(this IUrlHelper helper, string? action, object? values) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller: null, values: values, protocol: null, host: null, fragment: null); } @@ -78,10 +69,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? Action(this IUrlHelper helper, string? action, string? controller) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller, values: null, protocol: null, host: null, fragment: null); } @@ -97,10 +85,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? Action(this IUrlHelper helper, string? action, string? controller, object? values) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller, values, protocol: null, host: null, fragment: null); } @@ -131,10 +116,7 @@ public static class UrlHelperExtensions object? values, string? protocol) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller, values, protocol, host: null, fragment: null); } @@ -169,10 +151,7 @@ public static class UrlHelperExtensions string? protocol, string? host) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(action, controller, values, protocol, host, fragment: null); } @@ -209,10 +188,7 @@ public static class UrlHelperExtensions string? host, string? fragment) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.Action(new UrlActionContext() { @@ -233,10 +209,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? RouteUrl(this IUrlHelper helper, object? values) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(routeName: null, values: values, protocol: null, host: null, fragment: null); } @@ -249,10 +222,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? RouteUrl(this IUrlHelper helper, string? routeName) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(routeName, values: null, protocol: null, host: null, fragment: null); } @@ -267,10 +237,7 @@ public static class UrlHelperExtensions /// The generated URL. public static string? RouteUrl(this IUrlHelper helper, string? routeName, object? values) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(routeName, values, protocol: null, host: null, fragment: null); } @@ -299,10 +266,7 @@ public static class UrlHelperExtensions object? values, string? protocol) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(routeName, values, protocol, host: null, fragment: null); } @@ -335,10 +299,7 @@ public static class UrlHelperExtensions string? protocol, string? host) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(routeName, values, protocol, host, fragment: null); } @@ -373,10 +334,7 @@ public static class UrlHelperExtensions string? host, string? fragment) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.RouteUrl(new UrlRouteContext() { @@ -515,10 +473,7 @@ public static class UrlHelperExtensions string? host, string? fragment) { - if (urlHelper == null) - { - throw new ArgumentNullException(nameof(urlHelper)); - } + ArgumentNullException.ThrowIfNull(urlHelper); var routeValues = new RouteValueDictionary(values); var ambientValues = urlHelper.ActionContext.RouteData.Values; @@ -565,10 +520,7 @@ public static class UrlHelperExtensions string? host = null, string? fragment = null) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); var httpContext = helper.ActionContext.HttpContext; @@ -617,10 +569,7 @@ public static class UrlHelperExtensions string? host = null, string? fragment = null) { - if (urlHelper == null) - { - throw new ArgumentNullException(nameof(urlHelper)); - } + ArgumentNullException.ThrowIfNull(urlHelper); var httpContext = urlHelper.ActionContext.HttpContext; diff --git a/src/Mvc/Mvc.Core/src/ValidationProblemDetails.cs b/src/Mvc/Mvc.Core/src/ValidationProblemDetails.cs index 8bf68b607fdf..5583f2941ca0 100644 --- a/src/Mvc/Mvc.Core/src/ValidationProblemDetails.cs +++ b/src/Mvc/Mvc.Core/src/ValidationProblemDetails.cs @@ -34,10 +34,7 @@ public ValidationProblemDetails(ModelStateDictionary modelState) private static IDictionary CreateErrorDictionary(ModelStateDictionary modelState) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); var errorDictionary = new Dictionary(StringComparer.Ordinal); diff --git a/src/Mvc/Mvc.Core/src/VirtualFileResult.cs b/src/Mvc/Mvc.Core/src/VirtualFileResult.cs index dc27f840bdf9..b4f28f95a53f 100644 --- a/src/Mvc/Mvc.Core/src/VirtualFileResult.cs +++ b/src/Mvc/Mvc.Core/src/VirtualFileResult.cs @@ -59,10 +59,7 @@ public string FileName /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetRequiredService>(); return executor.ExecuteAsync(context, this); diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterConfigurationProviderTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterConfigurationProviderTest.cs index 20211f166ae6..e25caa1ab214 100644 --- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterConfigurationProviderTest.cs +++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterConfigurationProviderTest.cs @@ -118,14 +118,8 @@ public void Configure( IWebHostEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(loggerFactory); } } @@ -141,14 +135,8 @@ public void ConfigureProduction( IWebHostEnvironment hostingEnvironment, ILoggerFactory loggerFactory) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(loggerFactory); } } diff --git a/src/Mvc/Mvc.Core/test/ModelBinding/DefaultModelBindingContextTest.cs b/src/Mvc/Mvc.Core/test/ModelBinding/DefaultModelBindingContextTest.cs index 3e47e4d8a1a3..4d7b82d08403 100644 --- a/src/Mvc/Mvc.Core/test/ModelBinding/DefaultModelBindingContextTest.cs +++ b/src/Mvc/Mvc.Core/test/ModelBinding/DefaultModelBindingContextTest.cs @@ -185,10 +185,7 @@ private class TestModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); throw new NotImplementedException(); } diff --git a/src/Mvc/Mvc.Core/test/ModelBinding/StubModelBinder.cs b/src/Mvc/Mvc.Core/test/ModelBinding/StubModelBinder.cs index 5badeb3a6495..4d1664ef2827 100644 --- a/src/Mvc/Mvc.Core/test/ModelBinding/StubModelBinder.cs +++ b/src/Mvc/Mvc.Core/test/ModelBinding/StubModelBinder.cs @@ -59,10 +59,7 @@ public virtual async Task BindModelAsync(ModelBindingContext bindingContext) { BindModelCount += 1; - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); await _callback.Invoke(bindingContext); diff --git a/src/Mvc/Mvc.Cors/src/CorsApplicationModelProvider.cs b/src/Mvc/Mvc.Cors/src/CorsApplicationModelProvider.cs index 616fd3861188..06d9e8325458 100644 --- a/src/Mvc/Mvc.Cors/src/CorsApplicationModelProvider.cs +++ b/src/Mvc/Mvc.Cors/src/CorsApplicationModelProvider.cs @@ -22,20 +22,14 @@ public CorsApplicationModelProvider(IOptions mvcOptions) public void OnProvidersExecuted(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Intentionally empty. } public void OnProvidersExecuting(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!_mvcOptions.EnableEndpointRouting) { diff --git a/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilter.cs b/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilter.cs index 4eefed884c93..1838afa2071d 100644 --- a/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilter.cs +++ b/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilter.cs @@ -40,20 +40,9 @@ public CorsAuthorizationFilter( ICorsPolicyProvider policyProvider, ILoggerFactory loggerFactory) { - if (corsService == null) - { - throw new ArgumentNullException(nameof(corsService)); - } - - if (policyProvider == null) - { - throw new ArgumentNullException(nameof(policyProvider)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(corsService); + ArgumentNullException.ThrowIfNull(policyProvider); + ArgumentNullException.ThrowIfNull(loggerFactory); _corsService = corsService; _corsPolicyProvider = policyProvider; @@ -73,10 +62,7 @@ public CorsAuthorizationFilter( /// public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // If this filter is not closest to the action, it is not applicable. if (!context.IsEffectivePolicy(this)) diff --git a/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilterFactory.cs b/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilterFactory.cs index 8f4618696ee2..4b58924d4867 100644 --- a/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilterFactory.cs +++ b/src/Mvc/Mvc.Cors/src/CorsAuthorizationFilterFactory.cs @@ -33,10 +33,7 @@ public CorsAuthorizationFilterFactory(string? policyName) /// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); var filter = serviceProvider.GetRequiredService(); filter.PolicyName = _policyName; diff --git a/src/Mvc/Mvc.Cors/src/CorsHttpMethodActionConstraint.cs b/src/Mvc/Mvc.Cors/src/CorsHttpMethodActionConstraint.cs index 3046960560ea..c799f812cade 100644 --- a/src/Mvc/Mvc.Cors/src/CorsHttpMethodActionConstraint.cs +++ b/src/Mvc/Mvc.Cors/src/CorsHttpMethodActionConstraint.cs @@ -19,10 +19,7 @@ public CorsHttpMethodActionConstraint(HttpMethodActionConstraint constraint) public override bool Accept(ActionConstraintContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var methods = (ReadOnlyCollection)HttpMethods; if (methods.Count == 0) diff --git a/src/Mvc/Mvc.Cors/src/DependencyInjection/MvcCorsMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Cors/src/DependencyInjection/MvcCorsMvcCoreBuilderExtensions.cs index 52ca8a8db5a2..8fd55db81006 100644 --- a/src/Mvc/Mvc.Cors/src/DependencyInjection/MvcCorsMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Cors/src/DependencyInjection/MvcCorsMvcCoreBuilderExtensions.cs @@ -20,10 +20,7 @@ public static class MvcCorsMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddCors(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddCorsServices(builder.Services); return builder; @@ -39,15 +36,8 @@ public static IMvcCoreBuilder AddCors( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddCorsServices(builder.Services); builder.Services.Configure(setupAction); @@ -65,15 +55,8 @@ public static IMvcCoreBuilder ConfigureCors( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; diff --git a/src/Mvc/Mvc.Cors/src/DisableCorsAuthorizationFilter.cs b/src/Mvc/Mvc.Cors/src/DisableCorsAuthorizationFilter.cs index 114ddc705859..e350ff3a20af 100644 --- a/src/Mvc/Mvc.Cors/src/DisableCorsAuthorizationFilter.cs +++ b/src/Mvc/Mvc.Cors/src/DisableCorsAuthorizationFilter.cs @@ -21,10 +21,7 @@ internal sealed class DisableCorsAuthorizationFilter : ICorsAuthorizationFilter /// public Task OnAuthorizationAsync(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var accessControlRequestMethod = context.HttpContext.Request.Headers[CorsConstants.AccessControlRequestMethod]; diff --git a/src/Mvc/Mvc.DataAnnotations/src/CompareAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/CompareAttributeAdapter.cs index 43cbaff5ed3d..cb26a28aad80 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/CompareAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/CompareAttributeAdapter.cs @@ -21,10 +21,7 @@ public CompareAttributeAdapter(CompareAttribute attribute, IStringLocalizer? str public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-equalto", GetErrorMessage(context)); @@ -34,10 +31,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); var displayName = validationContext.ModelMetadata.GetDisplayName(); var otherPropertyDisplayName = CompareAttributeWrapper.GetOtherPropertyDisplayName( diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsClientModelValidatorProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsClientModelValidatorProvider.cs index 5a34f268c810..46e6cc00d879 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsClientModelValidatorProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsClientModelValidatorProvider.cs @@ -33,14 +33,8 @@ public DataAnnotationsClientModelValidatorProvider( IOptions options, IStringLocalizerFactory? stringLocalizerFactory) { - if (validationAttributeAdapterProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(validationAttributeAdapterProvider); + ArgumentNullException.ThrowIfNull(options); _validationAttributeAdapterProvider = validationAttributeAdapterProvider; _options = options; @@ -50,10 +44,7 @@ public DataAnnotationsClientModelValidatorProvider( /// public void CreateValidators(ClientValidatorProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); IStringLocalizer? stringLocalizer = null; if (_options.Value.DataAnnotationLocalizerProvider != null && _stringLocalizerFactory != null) { diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs index 60a197a7ac95..71ff84ba63ca 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsMetadataProvider.cs @@ -30,15 +30,8 @@ public DataAnnotationsMetadataProvider( IOptions localizationOptions, IStringLocalizerFactory? stringLocalizerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (localizationOptions == null) - { - throw new ArgumentNullException(nameof(localizationOptions)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(localizationOptions); _options = options; _localizationOptions = localizationOptions.Value; @@ -48,10 +41,7 @@ public DataAnnotationsMetadataProvider( /// public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var editableAttribute = context.Attributes.OfType().FirstOrDefault(); if (editableAttribute != null) @@ -63,10 +53,7 @@ public void CreateBindingMetadata(BindingMetadataProviderContext context) /// public void CreateDisplayMetadata(DisplayMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var attributes = context.Attributes; var dataTypeAttribute = attributes.OfType().FirstOrDefault(); @@ -310,10 +297,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Read interface .Count once rather than per iteration var contextAttributes = context.Attributes; diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidator.cs b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidator.cs index b45ad4c57b9f..4249c538ad3f 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidator.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidator.cs @@ -29,15 +29,8 @@ public DataAnnotationsModelValidator( ValidationAttribute attribute, IStringLocalizer? stringLocalizer) { - if (validationAttributeAdapterProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); - } - - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(validationAttributeAdapterProvider); + ArgumentNullException.ThrowIfNull(attribute); _validationAttributeAdapterProvider = validationAttributeAdapterProvider; Attribute = attribute; @@ -56,10 +49,7 @@ public DataAnnotationsModelValidator( /// An enumerable of the validation results. public IEnumerable Validate(ModelValidationContext validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); if (validationContext.ModelMetadata == null) { throw new ArgumentException( diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidatorProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidatorProvider.cs index 4c797d971279..ba1496a32c46 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidatorProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataAnnotationsModelValidatorProvider.cs @@ -33,14 +33,8 @@ public DataAnnotationsModelValidatorProvider( IOptions options, IStringLocalizerFactory? stringLocalizerFactory) { - if (validationAttributeAdapterProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(validationAttributeAdapterProvider); + ArgumentNullException.ThrowIfNull(options); _validationAttributeAdapterProvider = validationAttributeAdapterProvider; _options = options; diff --git a/src/Mvc/Mvc.DataAnnotations/src/DataTypeAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/DataTypeAttributeAdapter.cs index ee8859030dbf..01de4ef03840 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DataTypeAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DataTypeAttributeAdapter.cs @@ -28,10 +28,7 @@ public DataTypeAttributeAdapter(DataTypeAttribute attribute, string ruleName, IS public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, RuleName, GetErrorMessage(context)); @@ -40,10 +37,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/DefaultClientModelValidatorProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/DefaultClientModelValidatorProvider.cs index 2fc5e5f270d4..f1833e759dc0 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DefaultClientModelValidatorProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DefaultClientModelValidatorProvider.cs @@ -17,10 +17,7 @@ internal sealed class DefaultClientModelValidatorProvider : IClientModelValidato /// public void CreateValidators(ClientValidatorProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Perf: Avoid allocations var results = context.Results; diff --git a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsLocalizationOptionsSetup.cs b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsLocalizationOptionsSetup.cs index dadd338dad61..027ca13ddef7 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsLocalizationOptionsSetup.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsLocalizationOptionsSetup.cs @@ -14,10 +14,7 @@ internal sealed class MvcDataAnnotationsLocalizationOptionsSetup : IConfigureOpt /// public void Configure(MvcDataAnnotationsLocalizationOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.DataAnnotationLocalizerProvider = (modelType, stringLocalizerFactory) => stringLocalizerFactory.Create(modelType); diff --git a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcBuilderExtensions.cs b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcBuilderExtensions.cs index e51937ff8b30..f96498955c88 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcBuilderExtensions.cs @@ -17,10 +17,7 @@ public static class MvcDataAnnotationsMvcBuilderExtensions /// The . public static IMvcBuilder AddDataAnnotationsLocalization(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddDataAnnotationsLocalization(builder, setupAction: null); } @@ -36,10 +33,7 @@ public static IMvcBuilder AddDataAnnotationsLocalization( this IMvcBuilder builder, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); DataAnnotationsLocalizationServices.AddDataAnnotationsLocalizationServices( builder.Services, diff --git a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcCoreBuilderExtensions.cs index 04b1e59f91de..39d9dfa125cc 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcCoreBuilderExtensions.cs @@ -20,10 +20,7 @@ public static class MvcDataAnnotationsMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddDataAnnotations(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddDataAnnotationsServices(builder.Services); return builder; @@ -36,10 +33,7 @@ public static IMvcCoreBuilder AddDataAnnotations(this IMvcCoreBuilder builder) /// The . public static IMvcCoreBuilder AddDataAnnotationsLocalization(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddDataAnnotationsLocalization(builder, setupAction: null); } @@ -55,10 +49,7 @@ public static IMvcCoreBuilder AddDataAnnotationsLocalization( this IMvcCoreBuilder builder, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddDataAnnotationsLocalizationServices(builder.Services, setupAction); return builder; diff --git a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcOptionsSetup.cs b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcOptionsSetup.cs index 7d172b19d320..629cc7fc680e 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcOptionsSetup.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/DependencyInjection/MvcDataAnnotationsMvcOptionsSetup.cs @@ -21,15 +21,8 @@ public MvcDataAnnotationsMvcOptionsSetup( IValidationAttributeAdapterProvider validationAttributeAdapterProvider, IOptions dataAnnotationLocalizationOptions) { - if (validationAttributeAdapterProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); - } - - if (dataAnnotationLocalizationOptions == null) - { - throw new ArgumentNullException(nameof(dataAnnotationLocalizationOptions)); - } + ArgumentNullException.ThrowIfNull(validationAttributeAdapterProvider); + ArgumentNullException.ThrowIfNull(dataAnnotationLocalizationOptions); _validationAttributeAdapterProvider = validationAttributeAdapterProvider; _dataAnnotationLocalizationOptions = dataAnnotationLocalizationOptions; @@ -46,10 +39,7 @@ public MvcDataAnnotationsMvcOptionsSetup( public void Configure(MvcOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.ModelMetadataDetailsProviders.Add(new DataAnnotationsMetadataProvider( options, diff --git a/src/Mvc/Mvc.DataAnnotations/src/FileExtensionsAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/FileExtensionsAttributeAdapter.cs index d64750d54727..a0f5df5e2f95 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/FileExtensionsAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/FileExtensionsAttributeAdapter.cs @@ -29,10 +29,7 @@ public FileExtensionsAttributeAdapter(FileExtensionsAttribute attribute, IString /// public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-fileextensions", GetErrorMessage(context)); @@ -42,10 +39,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/MaxLengthAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/MaxLengthAttributeAdapter.cs index ec6f7ef71908..39dc8e063ca1 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/MaxLengthAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/MaxLengthAttributeAdapter.cs @@ -20,10 +20,7 @@ public MaxLengthAttributeAdapter(MaxLengthAttribute attribute, IStringLocalizer? public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-maxlength", GetErrorMessage(context)); @@ -33,10 +30,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/MinLengthAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/MinLengthAttributeAdapter.cs index dedb5d47ab12..ec81babf0b04 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/MinLengthAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/MinLengthAttributeAdapter.cs @@ -20,10 +20,7 @@ public MinLengthAttributeAdapter(MinLengthAttribute attribute, IStringLocalizer? public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-minlength", GetErrorMessage(context)); @@ -33,10 +30,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidator.cs b/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidator.cs index 812e642c7bfd..749528870fd2 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidator.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidator.cs @@ -15,10 +15,7 @@ internal sealed class NumericClientModelValidator : IClientModelValidator /// public void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-number", GetErrorMessage(context.ModelMetadata)); @@ -34,10 +31,7 @@ private static void MergeAttribute(IDictionary attributes, strin private static string GetErrorMessage(ModelMetadata modelMetadata) { - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } + ArgumentNullException.ThrowIfNull(modelMetadata); var messageProvider = modelMetadata.ModelBindingMessageProvider; var name = modelMetadata.DisplayName ?? modelMetadata.Name; diff --git a/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidatorProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidatorProvider.cs index 4c102b50c21e..308e9b5ec5eb 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidatorProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/NumericClientModelValidatorProvider.cs @@ -14,10 +14,7 @@ internal sealed class NumericClientModelValidatorProvider : IClientModelValidato /// public void CreateValidators(ClientValidatorProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var typeToValidate = context.ModelMetadata.UnderlyingOrModelType; diff --git a/src/Mvc/Mvc.DataAnnotations/src/RangeAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/RangeAttributeAdapter.cs index 31ddd8c34ca3..0ca08026539f 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/RangeAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/RangeAttributeAdapter.cs @@ -29,10 +29,7 @@ public RangeAttributeAdapter(RangeAttribute attribute, IStringLocalizer? stringL public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-range", GetErrorMessage(context)); @@ -43,10 +40,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/RegularExpressionAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/RegularExpressionAttributeAdapter.cs index 823a7340164b..cc3c85e30ddd 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/RegularExpressionAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/RegularExpressionAttributeAdapter.cs @@ -16,10 +16,7 @@ public RegularExpressionAttributeAdapter(RegularExpressionAttribute attribute, I public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-regex", GetErrorMessage(context)); @@ -29,10 +26,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/RequiredAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/RequiredAttributeAdapter.cs index 6f7e5c4bfc3a..75d4f05966dc 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/RequiredAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/RequiredAttributeAdapter.cs @@ -25,10 +25,7 @@ public RequiredAttributeAdapter(RequiredAttribute attribute, IStringLocalizer? s /// public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context)); @@ -37,10 +34,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName()); } diff --git a/src/Mvc/Mvc.DataAnnotations/src/StringLengthAttributeAdapter.cs b/src/Mvc/Mvc.DataAnnotations/src/StringLengthAttributeAdapter.cs index 554425ae0c02..532050b97661 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/StringLengthAttributeAdapter.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/StringLengthAttributeAdapter.cs @@ -23,10 +23,7 @@ public StringLengthAttributeAdapter(StringLengthAttribute attribute, IStringLoca /// public override void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-length", GetErrorMessage(context)); @@ -45,10 +42,7 @@ public override void AddValidation(ClientModelValidationContext context) /// public override string GetErrorMessage(ModelValidationContextBase validationContext) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } + ArgumentNullException.ThrowIfNull(validationContext); return GetErrorMessage( validationContext.ModelMetadata, diff --git a/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterOfTAttribute.cs b/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterOfTAttribute.cs index 0572f7bd7c77..601572b8eb4b 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterOfTAttribute.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterOfTAttribute.cs @@ -64,10 +64,7 @@ protected static bool MergeAttribute(IDictionary attributes, str /// Formatted error string. protected virtual string GetErrorMessage(ModelMetadata modelMetadata, params object[] arguments) { - if (modelMetadata == null) - { - throw new ArgumentNullException(nameof(modelMetadata)); - } + ArgumentNullException.ThrowIfNull(modelMetadata); if (_stringLocalizer != null && !string.IsNullOrEmpty(Attribute.ErrorMessage) && diff --git a/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterProvider.cs b/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterProvider.cs index 807263121f85..0a87780a9d05 100644 --- a/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterProvider.cs +++ b/src/Mvc/Mvc.DataAnnotations/src/ValidationAttributeAdapterProvider.cs @@ -19,10 +19,7 @@ public class ValidationAttributeAdapterProvider : IValidationAttributeAdapterPro /// An for the given attribute. public IAttributeAdapter? GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer? stringLocalizer) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); var type = attribute.GetType(); diff --git a/src/Mvc/Mvc.DataAnnotations/test/ModelValidationResultComparer.cs b/src/Mvc/Mvc.DataAnnotations/test/ModelValidationResultComparer.cs index 6d833c49fd4b..56e7169fa9cb 100644 --- a/src/Mvc/Mvc.DataAnnotations/test/ModelValidationResultComparer.cs +++ b/src/Mvc/Mvc.DataAnnotations/test/ModelValidationResultComparer.cs @@ -26,10 +26,7 @@ public bool Equals(ModelValidationResult x, ModelValidationResult y) public int GetHashCode(ModelValidationResult obj) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } + ArgumentNullException.ThrowIfNull(obj); return obj.MemberName.GetHashCode(); } diff --git a/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerable.cs b/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerable.cs index 2c09deb2a22d..cf2d8adbd66a 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerable.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerable.cs @@ -38,10 +38,7 @@ public DelegatingEnumerable() /// The wrapper provider for wrapping individual elements. public DelegatingEnumerable(IEnumerable source, IWrapperProvider elementWrapperProvider) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); _source = source; _wrapperProvider = elementWrapperProvider; diff --git a/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerator.cs b/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerator.cs index 37f7bb03d024..ce27d1572784 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerator.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/DelegatingEnumerator.cs @@ -25,10 +25,7 @@ public class DelegatingEnumerator : IEnumerator /// The wrapper provider to wrap individual elements. public DelegatingEnumerator(IEnumerator inner, IWrapperProvider? wrapperProvider) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullException.ThrowIfNull(inner); _inner = inner; _wrapperProvider = wrapperProvider; diff --git a/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcBuilderExtensions.cs b/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcBuilderExtensions.cs index 5cae9a9354c0..a2bf64cfeb28 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcBuilderExtensions.cs @@ -22,15 +22,8 @@ public static IMvcBuilder AddXmlOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -43,10 +36,7 @@ public static IMvcBuilder AddXmlOptions( /// The . public static IMvcBuilder AddXmlDataContractSerializerFormatters(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlDataContractSerializerFormatterServices(builder.Services); return builder; @@ -62,15 +52,8 @@ public static IMvcBuilder AddXmlDataContractSerializerFormatters( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddXmlDataContractSerializerFormatterServices(builder.Services); builder.Services.Configure(setupAction); @@ -84,10 +67,7 @@ public static IMvcBuilder AddXmlDataContractSerializerFormatters( /// The . public static IMvcBuilder AddXmlSerializerFormatters(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlSerializerFormatterServices(builder.Services); return builder; @@ -103,10 +83,7 @@ public static IMvcBuilder AddXmlSerializerFormatters( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlSerializerFormatterServices(builder.Services); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcCoreBuilderExtensions.cs index 288b9c1b9531..d861bebd6e33 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/DependencyInjection/MvcXmlMvcCoreBuilderExtensions.cs @@ -23,15 +23,8 @@ public static IMvcCoreBuilder AddXmlOptions( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -44,10 +37,7 @@ public static IMvcCoreBuilder AddXmlOptions( /// The . public static IMvcCoreBuilder AddXmlDataContractSerializerFormatters(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlDataContractSerializerFormatterServices(builder.Services); return builder; @@ -63,15 +53,8 @@ public static IMvcCoreBuilder AddXmlDataContractSerializerFormatters( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddXmlDataContractSerializerFormatterServices(builder.Services); builder.Services.Configure(setupAction); @@ -85,10 +68,7 @@ public static IMvcCoreBuilder AddXmlDataContractSerializerFormatters( /// The . public static IMvcCoreBuilder AddXmlSerializerFormatters(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlSerializerFormatterServices(builder.Services); return builder; @@ -104,10 +84,7 @@ public static IMvcCoreBuilder AddXmlSerializerFormatters( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddXmlSerializerFormatterServices(builder.Services); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProvider.cs b/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProvider.cs index 08e510188dff..869ad4353f76 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProvider.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProvider.cs @@ -26,10 +26,7 @@ public EnumerableWrapperProvider( Type sourceEnumerableOfT, IWrapperProvider? elementWrapperProvider) { - if (sourceEnumerableOfT == null) - { - throw new ArgumentNullException(nameof(sourceEnumerableOfT)); - } + ArgumentNullException.ThrowIfNull(sourceEnumerableOfT); var enumerableOfT = ClosedGenericMatcher.ExtractGenericInterface( sourceEnumerableOfT, diff --git a/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProviderFactory.cs b/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProviderFactory.cs index ac068933d937..e48743900880 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProviderFactory.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/EnumerableWrapperProviderFactory.cs @@ -20,10 +20,7 @@ public class EnumerableWrapperProviderFactory : IWrapperProviderFactory /// List of . public EnumerableWrapperProviderFactory(IEnumerable wrapperProviderFactories) { - if (wrapperProviderFactories == null) - { - throw new ArgumentNullException(nameof(wrapperProviderFactories)); - } + ArgumentNullException.ThrowIfNull(wrapperProviderFactories); _wrapperProviderFactories = wrapperProviderFactories; } @@ -36,10 +33,7 @@ public EnumerableWrapperProviderFactory(IEnumerable wra /// an interface and implements . public IWrapperProvider? GetProvider(WrapperProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.IsSerialization) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/ModelBinding/DataMemberRequiredBindingMetadataProvider.cs b/src/Mvc/Mvc.Formatters.Xml/src/ModelBinding/DataMemberRequiredBindingMetadataProvider.cs index 53b7b730e5d2..1c9b1b32dd85 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/ModelBinding/DataMemberRequiredBindingMetadataProvider.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/ModelBinding/DataMemberRequiredBindingMetadataProvider.cs @@ -15,10 +15,7 @@ public class DataMemberRequiredBindingMetadataProvider : IBindingMetadataProvide /// public void CreateBindingMetadata(BindingMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Types cannot be required; only properties can if (context.Key.MetadataKind != ModelMetadataKind.Property) diff --git a/src/Mvc/Mvc.Formatters.Xml/src/ProblemDetailsWrapper.cs b/src/Mvc/Mvc.Formatters.Xml/src/ProblemDetailsWrapper.cs index 3f5fd635864b..6282566b9e01 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/ProblemDetailsWrapper.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/ProblemDetailsWrapper.cs @@ -45,10 +45,7 @@ public ProblemDetailsWrapper(ProblemDetails problemDetails) /// public virtual void ReadXml(XmlReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (reader.IsEmptyElement) { @@ -75,10 +72,7 @@ public virtual void ReadXml(XmlReader reader) /// The name of the node. protected virtual void ReadValue(XmlReader reader, string name) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); var value = reader.ReadInnerXml(); @@ -177,10 +171,7 @@ public virtual void WriteXml(XmlWriter writer) object IUnwrappable.Unwrap(Type declaredType) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); return ProblemDetails; } diff --git a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs index bd85f8aebfcc..962edfe01c29 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapper.cs @@ -32,10 +32,7 @@ public SerializableErrorWrapper() /// The object that needs to be wrapped. public SerializableErrorWrapper(SerializableError error) { - if (error == null) - { - throw new ArgumentNullException(nameof(error)); - } + ArgumentNullException.ThrowIfNull(error); SerializableError = error; } @@ -109,10 +106,7 @@ public void WriteXml(XmlWriter writer) /// public object Unwrap(Type declaredType) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); return SerializableError; } diff --git a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProvider.cs b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProvider.cs index 0d73e639bed1..569c8738a07b 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProvider.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProvider.cs @@ -14,10 +14,7 @@ public class SerializableErrorWrapperProvider : IWrapperProvider /// public object? Wrap(object? original) { - if (original == null) - { - throw new ArgumentNullException(nameof(original)); - } + ArgumentNullException.ThrowIfNull(original); var error = original as SerializableError; if (error == null) diff --git a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProviderFactory.cs b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProviderFactory.cs index e193bbc22df5..94ef281ed509 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProviderFactory.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/SerializableErrorWrapperProviderFactory.cs @@ -21,10 +21,7 @@ public class SerializableErrorWrapperProviderFactory : IWrapperProviderFactory /// public IWrapperProvider? GetProvider(WrapperProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.DeclaredType == typeof(SerializableError)) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs b/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs index a95d8745d25c..489094b2df8f 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/ValidationProblemDetailsWrapper.cs @@ -38,10 +38,7 @@ public ValidationProblemDetailsWrapper(ValidationProblemDetails problemDetails) /// protected override void ReadValue(XmlReader reader, string name) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (string.Equals(name, ErrorKey, StringComparison.Ordinal)) { @@ -78,10 +75,7 @@ private void ReadErrorProperty(XmlReader reader) /// public override void WriteXml(XmlWriter writer) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); base.WriteXml(writer); @@ -114,10 +108,7 @@ public override void WriteXml(XmlWriter writer) object IUnwrappable.Unwrap(Type declaredType) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); return ProblemDetails; } diff --git a/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderContext.cs b/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderContext.cs index d3c93f7d8694..a57a035865b9 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderContext.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderContext.cs @@ -16,10 +16,7 @@ public class WrapperProviderContext /// serialization, otherwise . public WrapperProviderContext(Type declaredType, bool isSerialization) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); DeclaredType = declaredType; IsSerialization = isSerialization; diff --git a/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderFactoriesExtensions.cs b/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderFactoriesExtensions.cs index 79ff6055ef8a..2899f068fc66 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderFactoriesExtensions.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/WrapperProviderFactoriesExtensions.cs @@ -20,15 +20,8 @@ public static class WrapperProviderFactoriesExtensions this IEnumerable wrapperProviderFactories, WrapperProviderContext wrapperProviderContext) { - if (wrapperProviderFactories == null) - { - throw new ArgumentNullException(nameof(wrapperProviderFactories)); - } - - if (wrapperProviderContext == null) - { - throw new ArgumentNullException(nameof(wrapperProviderContext)); - } + ArgumentNullException.ThrowIfNull(wrapperProviderFactories); + ArgumentNullException.ThrowIfNull(wrapperProviderContext); foreach (var wrapperProviderFactory in wrapperProviderFactories) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerInputFormatter.cs b/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerInputFormatter.cs index 638bfc198b47..46b82e3c4211 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerInputFormatter.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerInputFormatter.cs @@ -76,10 +76,7 @@ public DataContractSerializerSettings SerializerSettings get => _serializerSettings; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _serializerSettings = value; } @@ -101,15 +98,8 @@ public virtual InputFormatterExceptionPolicy ExceptionPolicy /// public override async Task ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var request = context.HttpContext.Request; Stream readStream = new NonDisposableStream(request.Body); @@ -182,10 +172,7 @@ public override async Task ReadRequestBodyAsync(InputForma /// protected override bool CanReadType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); return GetCachedSerializer(GetSerializableType(type)) != null; } @@ -198,15 +185,8 @@ protected override bool CanReadType(Type type) /// The used during deserialization. protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding) { - if (readStream == null) - { - throw new ArgumentNullException(nameof(readStream)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(readStream); + ArgumentNullException.ThrowIfNull(encoding); return XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null); } @@ -218,10 +198,7 @@ protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding /// The type to which the XML will be deserialized. protected virtual Type GetSerializableType(Type declaredType) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); var wrapperProvider = WrapperProviderFactories.GetWrapperProvider( new WrapperProviderContext(declaredType, isSerialization: false)); @@ -236,10 +213,7 @@ protected virtual Type GetSerializableType(Type declaredType) /// The used during deserialization. protected virtual DataContractSerializer? CreateSerializer(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); try { @@ -260,10 +234,7 @@ protected virtual Type GetSerializableType(Type declaredType) /// The instance. protected virtual DataContractSerializer GetCachedSerializer(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (!_serializerCache.TryGetValue(type, out var serializer)) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerOutputFormatter.cs b/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerOutputFormatter.cs index 0f5082a43d74..5930bda0351a 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerOutputFormatter.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/XmlDataContractSerializerOutputFormatter.cs @@ -63,10 +63,7 @@ public XmlDataContractSerializerOutputFormatter(XmlWriterSettings writerSettings /// The . public XmlDataContractSerializerOutputFormatter(XmlWriterSettings writerSettings, ILoggerFactory loggerFactory) { - if (writerSettings == null) - { - throw new ArgumentNullException(nameof(writerSettings)); - } + ArgumentNullException.ThrowIfNull(writerSettings); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); @@ -108,10 +105,7 @@ public DataContractSerializerSettings SerializerSettings get => _serializerSettings; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _serializerSettings = value; } @@ -124,10 +118,7 @@ public DataContractSerializerSettings SerializerSettings /// The original or wrapped type provided by any s. protected virtual Type GetSerializableType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(new WrapperProviderContext( type, @@ -154,10 +145,7 @@ protected override bool CanWriteType(Type? type) /// A new instance of protected virtual DataContractSerializer? CreateSerializer(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); try { @@ -192,15 +180,8 @@ public virtual XmlWriter CreateXmlWriter( TextWriter writer, XmlWriterSettings xmlWriterSettings) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (xmlWriterSettings == null) - { - throw new ArgumentNullException(nameof(xmlWriterSettings)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(xmlWriterSettings); // We always close the TextWriter, so the XmlWriter shouldn't. xmlWriterSettings.CloseOutput = false; @@ -231,15 +212,8 @@ public virtual XmlWriter CreateXmlWriter( /// public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (selectedEncoding == null) - { - throw new ArgumentNullException(nameof(selectedEncoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(selectedEncoding); var writerSettings = WriterSettings.Clone(); writerSettings.Encoding = selectedEncoding; diff --git a/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerInputFormatter.cs b/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerInputFormatter.cs index 55bbcbf91bfb..857a6e9a7d70 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerInputFormatter.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerInputFormatter.cs @@ -82,15 +82,8 @@ public override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var request = context.HttpContext.Request; Stream readStream = new NonDisposableStream(request.Body); @@ -175,10 +168,7 @@ public override async Task ReadRequestBodyAsync( /// protected override bool CanReadType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); return GetCachedSerializer(GetSerializableType(type)) != null; } @@ -190,10 +180,7 @@ protected override bool CanReadType(Type type) /// The type to which the XML will be deserialized. protected virtual Type GetSerializableType(Type declaredType) { - if (declaredType == null) - { - throw new ArgumentNullException(nameof(declaredType)); - } + ArgumentNullException.ThrowIfNull(declaredType); var wrapperProvider = WrapperProviderFactories.GetWrapperProvider( new WrapperProviderContext(declaredType, isSerialization: false)); @@ -221,15 +208,8 @@ protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding /// The used during deserialization. protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding) { - if (readStream == null) - { - throw new ArgumentNullException(nameof(readStream)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(readStream); + ArgumentNullException.ThrowIfNull(encoding); return XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null); } @@ -259,10 +239,7 @@ protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding /// The instance. protected virtual XmlSerializer GetCachedSerializer(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); if (!_serializerCache.TryGetValue(type, out var serializer)) { diff --git a/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerOutputFormatter.cs b/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerOutputFormatter.cs index 5044a0cf60a3..42df12126e07 100644 --- a/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerOutputFormatter.cs +++ b/src/Mvc/Mvc.Formatters.Xml/src/XmlSerializerOutputFormatter.cs @@ -62,10 +62,7 @@ public XmlSerializerOutputFormatter(XmlWriterSettings writerSettings) /// The . public XmlSerializerOutputFormatter(XmlWriterSettings writerSettings, ILoggerFactory loggerFactory) { - if (writerSettings == null) - { - throw new ArgumentNullException(nameof(writerSettings)); - } + ArgumentNullException.ThrowIfNull(writerSettings); SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); @@ -103,10 +100,7 @@ public XmlSerializerOutputFormatter(XmlWriterSettings writerSettings, ILoggerFac /// The original or wrapped type provided by any . protected virtual Type GetSerializableType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(new WrapperProviderContext( type, @@ -133,10 +127,7 @@ protected override bool CanWriteType(Type? type) /// A new instance of protected virtual XmlSerializer? CreateSerializer(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); try { @@ -168,15 +159,8 @@ public virtual XmlWriter CreateXmlWriter( TextWriter writer, XmlWriterSettings xmlWriterSettings) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (xmlWriterSettings == null) - { - throw new ArgumentNullException(nameof(xmlWriterSettings)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(xmlWriterSettings); // We always close the TextWriter, so the XmlWriter shouldn't. xmlWriterSettings.CloseOutput = false; @@ -207,15 +191,8 @@ public virtual XmlWriter CreateXmlWriter( /// public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (selectedEncoding == null) - { - throw new ArgumentNullException(nameof(selectedEncoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(selectedEncoding); var writerSettings = WriterSettings.Clone(); writerSettings.Encoding = selectedEncoding; diff --git a/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcBuilderExtensions.cs b/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcBuilderExtensions.cs index 23e7ea2c6770..ed9ee7e6d748 100644 --- a/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcBuilderExtensions.cs @@ -20,10 +20,7 @@ public static class MvcLocalizationMvcBuilderExtensions /// The . public static IMvcBuilder AddViewLocalization(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix); } @@ -38,10 +35,7 @@ public static IMvcBuilder AddViewLocalization( this IMvcBuilder builder, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddViewLocalization(builder, format, setupAction: null); return builder; @@ -57,10 +51,7 @@ public static IMvcBuilder AddViewLocalization( this IMvcBuilder builder, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix, setupAction); return builder; @@ -78,10 +69,7 @@ public static IMvcBuilder AddViewLocalization( LanguageViewLocationExpanderFormat format, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); MvcLocalizationServices.AddLocalizationServices(builder.Services, format, setupAction); return builder; @@ -99,10 +87,7 @@ public static IMvcBuilder AddViewLocalization( /// public static IMvcBuilder AddMvcLocalization(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -126,10 +111,7 @@ public static IMvcBuilder AddMvcLocalization( this IMvcBuilder builder, Action? localizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -153,10 +135,7 @@ public static IMvcBuilder AddMvcLocalization( this IMvcBuilder builder, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -183,10 +162,7 @@ public static IMvcBuilder AddMvcLocalization( Action? localizationOptionsSetupAction, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -211,10 +187,7 @@ public static IMvcBuilder AddMvcLocalization( this IMvcBuilder builder, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -242,10 +215,7 @@ public static IMvcBuilder AddMvcLocalization( Action? localizationOptionsSetupAction, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -272,10 +242,7 @@ public static IMvcBuilder AddMvcLocalization( LanguageViewLocationExpanderFormat format, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -305,10 +272,7 @@ public static IMvcBuilder AddMvcLocalization( LanguageViewLocationExpanderFormat format, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return builder .AddViewLocalization(format, localizationOptionsSetupAction) diff --git a/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcCoreBuilderExtensions.cs index 9d500adc409e..91842ad3c8e7 100644 --- a/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Localization/src/DependencyInjection/MvcLocalizationMvcCoreBuilderExtensions.cs @@ -25,10 +25,7 @@ public static class MvcLocalizationMvcCoreBuilderExtensions /// public static IMvcCoreBuilder AddViewLocalization(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix); } @@ -48,10 +45,7 @@ public static IMvcCoreBuilder AddViewLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AddViews(); builder.AddRazorViewEngine(); @@ -75,10 +69,7 @@ public static IMvcCoreBuilder AddViewLocalization( this IMvcCoreBuilder builder, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix, setupAction); } @@ -100,10 +91,7 @@ public static IMvcCoreBuilder AddViewLocalization( LanguageViewLocationExpanderFormat format, Action? setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AddViews(); builder.AddRazorViewEngine(); @@ -124,10 +112,7 @@ public static IMvcCoreBuilder AddViewLocalization( /// public static IMvcCoreBuilder AddMvcLocalization(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -151,10 +136,7 @@ public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action? localizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -178,10 +160,7 @@ public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -208,10 +187,7 @@ public static IMvcCoreBuilder AddMvcLocalization( Action? localizationOptionsSetupAction, LanguageViewLocationExpanderFormat format) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -236,10 +212,7 @@ public static IMvcCoreBuilder AddMvcLocalization( this IMvcCoreBuilder builder, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -267,10 +240,7 @@ public static IMvcCoreBuilder AddMvcLocalization( Action? localizationOptionsSetupAction, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -297,10 +267,7 @@ public static IMvcCoreBuilder AddMvcLocalization( LanguageViewLocationExpanderFormat format, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return AddMvcLocalization( builder, @@ -330,10 +297,7 @@ public static IMvcCoreBuilder AddMvcLocalization( LanguageViewLocationExpanderFormat format, Action? dataAnnotationsLocalizationOptionsSetupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); return builder .AddViewLocalization(format, localizationOptionsSetupAction) diff --git a/src/Mvc/Mvc.Localization/src/HtmlLocalizer.cs b/src/Mvc/Mvc.Localization/src/HtmlLocalizer.cs index 8bffed1a394b..c8ee35802296 100644 --- a/src/Mvc/Mvc.Localization/src/HtmlLocalizer.cs +++ b/src/Mvc/Mvc.Localization/src/HtmlLocalizer.cs @@ -19,10 +19,7 @@ public class HtmlLocalizer : IHtmlLocalizer /// The to read strings from. public HtmlLocalizer(IStringLocalizer localizer) { - if (localizer == null) - { - throw new ArgumentNullException(nameof(localizer)); - } + ArgumentNullException.ThrowIfNull(localizer); _localizer = localizer; } @@ -32,10 +29,7 @@ public virtual LocalizedHtmlString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return ToHtmlString(_localizer[name]); } @@ -46,10 +40,7 @@ public virtual LocalizedHtmlString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return ToHtmlString(_localizer[name], arguments); } @@ -58,10 +49,7 @@ public virtual LocalizedHtmlString this[string name] /// public virtual LocalizedString GetString(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer[name]; } @@ -69,10 +57,7 @@ public virtual LocalizedString GetString(string name) /// public virtual LocalizedString GetString(string name, params object[] arguments) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer[name, arguments]; } diff --git a/src/Mvc/Mvc.Localization/src/HtmlLocalizerExtensions.cs b/src/Mvc/Mvc.Localization/src/HtmlLocalizerExtensions.cs index 4c9942b498ca..a28e8500731c 100644 --- a/src/Mvc/Mvc.Localization/src/HtmlLocalizerExtensions.cs +++ b/src/Mvc/Mvc.Localization/src/HtmlLocalizerExtensions.cs @@ -18,15 +18,8 @@ public static class HtmlLocalizerExtensions /// The resource. public static LocalizedHtmlString GetHtml(this IHtmlLocalizer htmlLocalizer, string name) { - if (htmlLocalizer == null) - { - throw new ArgumentNullException(nameof(htmlLocalizer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(htmlLocalizer); + ArgumentNullException.ThrowIfNull(name); return htmlLocalizer[name]; } @@ -40,15 +33,8 @@ public static LocalizedHtmlString GetHtml(this IHtmlLocalizer htmlLocalizer, str /// The resource. public static LocalizedHtmlString GetHtml(this IHtmlLocalizer htmlLocalizer, string name, params object[] arguments) { - if (htmlLocalizer == null) - { - throw new ArgumentNullException(nameof(htmlLocalizer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(htmlLocalizer); + ArgumentNullException.ThrowIfNull(name); return htmlLocalizer[name, arguments]; } @@ -60,10 +46,7 @@ public static LocalizedHtmlString GetHtml(this IHtmlLocalizer htmlLocalizer, str /// The string resources. public static IEnumerable GetAllStrings(this IHtmlLocalizer htmlLocalizer) { - if (htmlLocalizer == null) - { - throw new ArgumentNullException(nameof(htmlLocalizer)); - } + ArgumentNullException.ThrowIfNull(htmlLocalizer); return htmlLocalizer.GetAllStrings(includeParentCultures: true); } diff --git a/src/Mvc/Mvc.Localization/src/HtmlLocalizerFactory.cs b/src/Mvc/Mvc.Localization/src/HtmlLocalizerFactory.cs index 05c239cc5112..df4e7c83ef75 100644 --- a/src/Mvc/Mvc.Localization/src/HtmlLocalizerFactory.cs +++ b/src/Mvc/Mvc.Localization/src/HtmlLocalizerFactory.cs @@ -19,10 +19,7 @@ public class HtmlLocalizerFactory : IHtmlLocalizerFactory /// The . public HtmlLocalizerFactory(IStringLocalizerFactory localizerFactory) { - if (localizerFactory == null) - { - throw new ArgumentNullException(nameof(localizerFactory)); - } + ArgumentNullException.ThrowIfNull(localizerFactory); _factory = localizerFactory; } @@ -34,10 +31,7 @@ public HtmlLocalizerFactory(IStringLocalizerFactory localizerFactory) /// The . public virtual IHtmlLocalizer Create(Type resourceSource) { - if (resourceSource == null) - { - throw new ArgumentNullException(nameof(resourceSource)); - } + ArgumentNullException.ThrowIfNull(resourceSource); return new HtmlLocalizer(_factory.Create(resourceSource)); } @@ -50,15 +44,8 @@ public virtual IHtmlLocalizer Create(Type resourceSource) /// The . public virtual IHtmlLocalizer Create(string baseName, string location) { - if (baseName == null) - { - throw new ArgumentNullException(nameof(baseName)); - } - - if (location == null) - { - throw new ArgumentNullException(nameof(location)); - } + ArgumentNullException.ThrowIfNull(baseName); + ArgumentNullException.ThrowIfNull(location); var localizer = _factory.Create(baseName, location); return new HtmlLocalizer(localizer); diff --git a/src/Mvc/Mvc.Localization/src/HtmlLocalizerOfT.cs b/src/Mvc/Mvc.Localization/src/HtmlLocalizerOfT.cs index b9c78a5f47bf..03d0aa7292bd 100644 --- a/src/Mvc/Mvc.Localization/src/HtmlLocalizerOfT.cs +++ b/src/Mvc/Mvc.Localization/src/HtmlLocalizerOfT.cs @@ -28,10 +28,7 @@ public virtual LocalizedHtmlString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer[name]; } @@ -42,10 +39,7 @@ public virtual LocalizedHtmlString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer[name, arguments]; } @@ -54,10 +48,7 @@ public virtual LocalizedHtmlString this[string name] /// public virtual LocalizedString GetString(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer.GetString(name); } @@ -65,10 +56,7 @@ public virtual LocalizedString GetString(string name) /// public virtual LocalizedString GetString(string name, params object[] arguments) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return _localizer.GetString(name, arguments); } diff --git a/src/Mvc/Mvc.Localization/src/LocalizedHtmlString.cs b/src/Mvc/Mvc.Localization/src/LocalizedHtmlString.cs index d53d077b9417..6a46a7ad40a4 100644 --- a/src/Mvc/Mvc.Localization/src/LocalizedHtmlString.cs +++ b/src/Mvc/Mvc.Localization/src/LocalizedHtmlString.cs @@ -43,20 +43,9 @@ public LocalizedHtmlString(string name, string value, bool isResourceNotFound) /// The values to format the with. public LocalizedHtmlString(string name, string value, bool isResourceNotFound, params object[] arguments) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (arguments == null) - { - throw new ArgumentNullException(nameof(arguments)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(arguments); Name = name; Value = value; @@ -82,15 +71,8 @@ public LocalizedHtmlString(string name, string value, bool isResourceNotFound, p /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); var formattableString = new HtmlFormattableString(Value, _arguments); formattableString.WriteTo(writer, encoder); diff --git a/src/Mvc/Mvc.Localization/src/ViewLocalizer.cs b/src/Mvc/Mvc.Localization/src/ViewLocalizer.cs index 008c6744acb8..14deaeceff0a 100644 --- a/src/Mvc/Mvc.Localization/src/ViewLocalizer.cs +++ b/src/Mvc/Mvc.Localization/src/ViewLocalizer.cs @@ -27,15 +27,8 @@ public class ViewLocalizer : IViewLocalizer, IViewContextAware /// The . public ViewLocalizer(IHtmlLocalizerFactory localizerFactory, IWebHostEnvironment hostingEnvironment) { - if (localizerFactory == null) - { - throw new ArgumentNullException(nameof(localizerFactory)); - } - - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(localizerFactory); + ArgumentNullException.ThrowIfNull(hostingEnvironment); if (string.IsNullOrEmpty(hostingEnvironment.ApplicationName)) { @@ -51,10 +44,7 @@ public virtual LocalizedHtmlString this[string key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _localizer[key]; } @@ -65,10 +55,7 @@ public virtual LocalizedHtmlString this[string key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _localizer[key, arguments]; } @@ -90,10 +77,7 @@ public IEnumerable GetAllStrings(bool includeParentCultures) => /// The . public void Contextualize(ViewContext viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); // Given a view path "/Views/Home/Index.cshtml" we want a baseName like "MyApplication.Views.Home.Index" var path = viewContext.ExecutingFilePath; diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/MvcNewtonsoftJsonOptionsExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/MvcNewtonsoftJsonOptionsExtensions.cs index 4d4c0f6a202a..4a60b2b4a1a5 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/MvcNewtonsoftJsonOptionsExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/MvcNewtonsoftJsonOptionsExtensions.cs @@ -25,10 +25,7 @@ public static class MvcNewtonsoftJsonOptionsExtensions /// with camel case settings. public static MvcNewtonsoftJsonOptions UseCamelCasing(this MvcNewtonsoftJsonOptions options, bool processDictionaryKeys) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.SerializerSettings.ContractResolver is DefaultContractResolver resolver) { @@ -63,10 +60,7 @@ public static MvcNewtonsoftJsonOptions UseCamelCasing(this MvcNewtonsoftJsonOpti /// with member casing settings. public static MvcNewtonsoftJsonOptions UseMemberCasing(this MvcNewtonsoftJsonOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.SerializerSettings.ContractResolver is DefaultContractResolver resolver) { diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcBuilderExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcBuilderExtensions.cs index 9bef693a2ae6..97a8b2364e93 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcBuilderExtensions.cs @@ -17,10 +17,7 @@ public static class NewtonsoftJsonMvcBuilderExtensions /// The . public static IMvcBuilder AddNewtonsoftJson(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(builder.Services); return builder; @@ -36,15 +33,8 @@ public static IMvcBuilder AddNewtonsoftJson( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(builder.Services); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs index 8011c4dcd095..41b48dbd3d12 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs @@ -26,10 +26,7 @@ public static class NewtonsoftJsonMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddNewtonsoftJson(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddServicesCore(builder.Services); return builder; @@ -45,15 +42,8 @@ public static IMvcCoreBuilder AddNewtonsoftJson( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddServicesCore(builder.Services); diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcOptionsSetup.cs b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcOptionsSetup.cs index 9d70cff85e2e..dabb1584c60a 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcOptionsSetup.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcOptionsSetup.cs @@ -30,25 +30,10 @@ public NewtonsoftJsonMvcOptionsSetup( ArrayPool charPool, ObjectPoolProvider objectPoolProvider) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (jsonOptions == null) - { - throw new ArgumentNullException(nameof(jsonOptions)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } - - if (objectPoolProvider == null) - { - throw new ArgumentNullException(nameof(objectPoolProvider)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(jsonOptions); + ArgumentNullException.ThrowIfNull(charPool); + ArgumentNullException.ThrowIfNull(objectPoolProvider); _loggerFactory = loggerFactory; _jsonOptions = jsonOptions.Value; diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/JsonArrayPool.cs b/src/Mvc/Mvc.NewtonsoftJson/src/JsonArrayPool.cs index b1d214915242..876c93a9f3f7 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/JsonArrayPool.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/JsonArrayPool.cs @@ -12,10 +12,7 @@ internal sealed class JsonArrayPool : IArrayPool public JsonArrayPool(ArrayPool inner) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullException.ThrowIfNull(inner); _inner = inner; } @@ -27,10 +24,7 @@ public T[] Rent(int minimumLength) public void Return(T[]? array) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); _inner.Return(array); } diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/JsonHelperExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/JsonHelperExtensions.cs index a5ce1ca198ec..ee7ecc5ca744 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/JsonHelperExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/JsonHelperExtensions.cs @@ -31,10 +31,7 @@ public static IHtmlContent Serialize( object value, JsonSerializerSettings serializerSettings) { - if (jsonHelper == null) - { - throw new ArgumentNullException(nameof(jsonHelper)); - } + ArgumentNullException.ThrowIfNull(jsonHelper); if (!(jsonHelper is NewtonsoftJsonHelper newtonsoftJsonHelper)) { @@ -47,15 +44,8 @@ public static IHtmlContent Serialize( throw new ArgumentException(message, nameof(jsonHelper)); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (serializerSettings == null) - { - throw new ArgumentNullException(nameof(serializerSettings)); - } + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(serializerSettings); return newtonsoftJsonHelper.Serialize(value, serializerSettings); } diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchExtensions.cs b/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchExtensions.cs index cfbf72308c3e..520f86af4a91 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchExtensions.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchExtensions.cs @@ -22,20 +22,9 @@ public static void ApplyTo( T objectToApplyTo, ModelStateDictionary modelState) where T : class { - if (patchDoc == null) - { - throw new ArgumentNullException(nameof(patchDoc)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(patchDoc); + ArgumentNullException.ThrowIfNull(objectToApplyTo); + ArgumentNullException.ThrowIfNull(modelState); patchDoc.ApplyTo(objectToApplyTo, modelState, prefix: string.Empty); } @@ -53,20 +42,9 @@ public static void ApplyTo( ModelStateDictionary modelState, string prefix) where T : class { - if (patchDoc == null) - { - throw new ArgumentNullException(nameof(patchDoc)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(patchDoc); + ArgumentNullException.ThrowIfNull(objectToApplyTo); + ArgumentNullException.ThrowIfNull(modelState); patchDoc.ApplyTo(objectToApplyTo, jsonPatchError => { diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchOperationsArrayProvider.cs b/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchOperationsArrayProvider.cs index f27a6eb5861b..cb44d6a3b28e 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchOperationsArrayProvider.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/JsonPatchOperationsArrayProvider.cs @@ -35,10 +35,7 @@ public JsonPatchOperationsArrayProvider(IModelMetadataProvider modelMetadataProv /// public void OnProvidersExecuting(ApiDescriptionProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var result in context.Results) { diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj b/src/Mvc/Mvc.NewtonsoftJson/src/Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj index e45237cb68bd..71271939fa15 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj +++ b/src/Mvc/Mvc.NewtonsoftJson/src/Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj @@ -24,6 +24,8 @@ + + diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonHelper.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonHelper.cs index 61d0c970cba9..6be363b58b93 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonHelper.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonHelper.cs @@ -29,15 +29,8 @@ internal sealed class NewtonsoftJsonHelper : IJsonHelper /// public NewtonsoftJsonHelper(IOptions options, ArrayPool charPool) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(charPool); _defaultSettingsJsonSerializer = CreateHtmlSafeSerializer(options.Value.SerializerSettings); _charPool = new JsonArrayPool(charPool); @@ -50,10 +43,7 @@ public IHtmlContent Serialize(object value) public IHtmlContent Serialize(object value, JsonSerializerSettings serializerSettings) { - if (serializerSettings == null) - { - throw new ArgumentNullException(nameof(serializerSettings)); - } + ArgumentNullException.ThrowIfNull(serializerSettings); var jsonSerializer = CreateHtmlSafeSerializer(serializerSettings); return Serialize(value, jsonSerializer); diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonInputFormatter.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonInputFormatter.cs index 77b4343629ee..81e33dc6092b 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonInputFormatter.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonInputFormatter.cs @@ -48,25 +48,10 @@ public NewtonsoftJsonInputFormatter( MvcOptions options, MvcNewtonsoftJsonOptions jsonOptions) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (serializerSettings == null) - { - throw new ArgumentNullException(nameof(serializerSettings)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } - - if (objectPoolProvider == null) - { - throw new ArgumentNullException(nameof(objectPoolProvider)); - } + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(serializerSettings); + ArgumentNullException.ThrowIfNull(charPool); + ArgumentNullException.ThrowIfNull(objectPoolProvider); _logger = logger; SerializerSettings = serializerSettings; @@ -110,15 +95,8 @@ public override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var httpContext = context.HttpContext; var request = httpContext.Request; diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonOutputFormatter.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonOutputFormatter.cs index a6f8703ce498..faa290950625 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonOutputFormatter.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonOutputFormatter.cs @@ -58,15 +58,8 @@ public NewtonsoftJsonOutputFormatter( MvcOptions mvcOptions, MvcNewtonsoftJsonOptions? jsonOptions) { - if (serializerSettings == null) - { - throw new ArgumentNullException(nameof(serializerSettings)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } + ArgumentNullException.ThrowIfNull(serializerSettings); + ArgumentNullException.ThrowIfNull(charPool); SerializerSettings = serializerSettings; _charPool = new JsonArrayPool(charPool); @@ -98,10 +91,7 @@ public NewtonsoftJsonOutputFormatter( /// The used during serialization. protected virtual JsonWriter CreateJsonWriter(TextWriter writer) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); var jsonWriter = new JsonTextWriter(writer) { @@ -143,15 +133,8 @@ protected virtual JsonSerializer CreateJsonSerializer(OutputFormatterWriteContex /// public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (selectedEncoding == null) - { - throw new ArgumentNullException(nameof(selectedEncoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(selectedEncoding); // Compat mode for derived options _jsonOptions ??= context.HttpContext.RequestServices.GetRequiredService>().Value; diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs index 9f4a2b00e9d7..2eb4358277c9 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs @@ -62,15 +62,8 @@ public override async Task ReadRequestBodyAsync( InputFormatterContext context, Encoding encoding) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(encoding); var result = await base.ReadRequestBodyAsync(context, encoding); if (!result.HasError) @@ -87,10 +80,7 @@ public override async Task ReadRequestBodyAsync( /// public override bool CanRead(InputFormatterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var modelType = context.ModelType; if (!typeof(IJsonPatchDocument).IsAssignableFrom(modelType) || diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs index ac1b085298f1..9b43a0ab11ce 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs @@ -46,25 +46,10 @@ public NewtonsoftJsonResultExecutor( IOptions jsonOptions, ArrayPool charPool) { - if (writerFactory == null) - { - throw new ArgumentNullException(nameof(writerFactory)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (jsonOptions == null) - { - throw new ArgumentNullException(nameof(jsonOptions)); - } - - if (charPool == null) - { - throw new ArgumentNullException(nameof(charPool)); - } + ArgumentNullException.ThrowIfNull(writerFactory); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(jsonOptions); + ArgumentNullException.ThrowIfNull(charPool); _writerFactory = writerFactory; _logger = logger; @@ -82,15 +67,8 @@ public NewtonsoftJsonResultExecutor( /// A which will complete when writing has completed. public async Task ExecuteAsync(ActionContext context, JsonResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var jsonSerializerSettings = GetSerializerSettings(result); diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonValidationMetadataProvider.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonValidationMetadataProvider.cs index 1fe66d72c685..21a7708f1620 100644 --- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonValidationMetadataProvider.cs +++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonValidationMetadataProvider.cs @@ -29,10 +29,7 @@ public NewtonsoftJsonValidationMetadataProvider() /// The to be used to configure the metadata provider. public NewtonsoftJsonValidationMetadataProvider(NamingStrategy namingStrategy) { - if (namingStrategy == null) - { - throw new ArgumentNullException(nameof(namingStrategy)); - } + ArgumentNullException.ThrowIfNull(namingStrategy); _jsonNamingPolicy = namingStrategy; } @@ -40,10 +37,7 @@ public NewtonsoftJsonValidationMetadataProvider(NamingStrategy namingStrategy) /// public void CreateDisplayMetadata(DisplayMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var propertyName = ReadPropertyNameFrom(context.Attributes); @@ -56,10 +50,7 @@ public void CreateDisplayMetadata(DisplayMetadataProviderContext context) /// public void CreateValidationMetadata(ValidationMetadataProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var propertyName = ReadPropertyNameFrom(context.Attributes); diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/ChecksumValidator.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/ChecksumValidator.cs index d162d22a9675..41c5ca4b5376 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/ChecksumValidator.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/ChecksumValidator.cs @@ -12,10 +12,7 @@ internal static class ChecksumValidator { public static bool IsRecompilationSupported(RazorCompiledItem item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); // A Razor item only supports recompilation if its primary source file has a checksum. // @@ -29,15 +26,8 @@ public static bool IsRecompilationSupported(RazorCompiledItem item) // disk. public static bool IsItemValid(RazorProjectFileSystem fileSystem, RazorCompiledItem item) { - if (fileSystem == null) - { - throw new ArgumentNullException(nameof(fileSystem)); - } - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(item); var checksums = item.GetChecksumMetadata(); diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/CompilationFailedException.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/CompilationFailedException.cs index 3e459b559209..be4bd62488fd 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/CompilationFailedException.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/CompilationFailedException.cs @@ -12,10 +12,7 @@ public CompilationFailedException( IEnumerable compilationFailures) : base(FormatMessage(compilationFailures)) { - if (compilationFailures == null) - { - throw new ArgumentNullException(nameof(compilationFailures)); - } + ArgumentNullException.ThrowIfNull(compilationFailures); CompilationFailures = compilationFailures; } diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/MvcRazorRuntimeCompilationOptionsSetup.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/MvcRazorRuntimeCompilationOptionsSetup.cs index 3cd6213b9de8..33eae53219ab 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/MvcRazorRuntimeCompilationOptionsSetup.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/MvcRazorRuntimeCompilationOptionsSetup.cs @@ -17,10 +17,7 @@ public MvcRazorRuntimeCompilationOptionsSetup(IWebHostEnvironment hostingEnviron public void Configure(MvcRazorRuntimeCompilationOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.FileProviders.Add(_hostingEnvironment.ContentRootFileProvider); } diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcBuilderExtensions.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcBuilderExtensions.cs index a15ce389594f..c6518101b0ee 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcBuilderExtensions.cs @@ -17,10 +17,7 @@ public static class RazorRuntimeCompilationMvcBuilderExtensions /// The . public static IMvcBuilder AddRazorRuntimeCompilation(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); RazorRuntimeCompilationMvcCoreBuilderExtensions.AddServices(builder.Services); return builder; @@ -34,15 +31,8 @@ public static IMvcBuilder AddRazorRuntimeCompilation(this IMvcBuilder builder) /// The . public static IMvcBuilder AddRazorRuntimeCompilation(this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); RazorRuntimeCompilationMvcCoreBuilderExtensions.AddServices(builder.Services); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcCoreBuilderExtensions.cs index 7063f467116c..c74402f64e69 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/DependencyInjection/RazorRuntimeCompilationMvcCoreBuilderExtensions.cs @@ -29,10 +29,7 @@ public static class RazorRuntimeCompilationMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddRazorRuntimeCompilation(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddServices(builder.Services); return builder; @@ -46,15 +43,8 @@ public static IMvcCoreBuilder AddRazorRuntimeCompilation(this IMvcCoreBuilder bu /// The . public static IMvcCoreBuilder AddRazorRuntimeCompilation(this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddServices(builder.Services); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectFileSystem.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectFileSystem.cs index df68fab9a28e..d6045545f4da 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectFileSystem.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectFileSystem.cs @@ -15,15 +15,8 @@ internal sealed class FileProviderRazorProjectFileSystem : RazorProjectFileSyste public FileProviderRazorProjectFileSystem(RuntimeCompilationFileProvider fileProvider, IWebHostEnvironment hostingEnvironment) { - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } - - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } + ArgumentNullException.ThrowIfNull(fileProvider); + ArgumentNullException.ThrowIfNull(hostingEnvironment); _fileProvider = fileProvider; _hostingEnvironment = hostingEnvironment; diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageActionDescriptorChangeProvider.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageActionDescriptorChangeProvider.cs index 623f60048b3b..9da98dab06ea 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageActionDescriptorChangeProvider.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageActionDescriptorChangeProvider.cs @@ -22,20 +22,9 @@ public PageActionDescriptorChangeProvider( RuntimeCompilationFileProvider fileProvider, IOptions razorPagesOptions) { - if (projectEngine == null) - { - throw new ArgumentNullException(nameof(projectEngine)); - } - - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } - - if (razorPagesOptions == null) - { - throw new ArgumentNullException(nameof(razorPagesOptions)); - } + ArgumentNullException.ThrowIfNull(projectEngine); + ArgumentNullException.ThrowIfNull(fileProvider); + ArgumentNullException.ThrowIfNull(razorPagesOptions); _fileProvider = fileProvider; diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageDirectiveFeature.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageDirectiveFeature.cs index 6a286a57ff4e..5c48d3677925 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageDirectiveFeature.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageDirectiveFeature.cs @@ -31,10 +31,7 @@ internal static partial class PageDirectiveFeature public static bool TryGetPageDirective(ILogger logger, RazorProjectItem projectItem, [NotNullWhen(true)] out string? template) { - if (projectItem == null) - { - throw new ArgumentNullException(nameof(projectItem)); - } + ArgumentNullException.ThrowIfNull(projectItem); var codeDocument = PageDirectiveEngine.Process(projectItem); diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageLoaderMatcherPolicy.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageLoaderMatcherPolicy.cs index 742a62f43785..4c33f0d9e6d6 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageLoaderMatcherPolicy.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/PageLoaderMatcherPolicy.cs @@ -32,10 +32,7 @@ public PageLoaderMatcherPolicy(PageLoader? loader) public bool AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); // We don't mark Pages as dynamic endpoints because that causes all matcher policies // to run in *slow mode*. Instead we produce the same metadata for things that would affect matcher @@ -57,15 +54,8 @@ public bool AppliesToEndpoints(IReadOnlyList endpoints) public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); for (var i = 0; i < candidates.Count; i++) { diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeCompilationFileProvider.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeCompilationFileProvider.cs index 4595924145d2..1a912345216b 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeCompilationFileProvider.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeCompilationFileProvider.cs @@ -13,10 +13,7 @@ internal sealed class RuntimeCompilationFileProvider public RuntimeCompilationFileProvider(IOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); _options = options.Value; } diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeViewCompiler.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeViewCompiler.cs index 596a76608240..11a1da7d41ef 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeViewCompiler.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RuntimeViewCompiler.cs @@ -39,30 +39,11 @@ public RuntimeViewCompiler( IList precompiledViews, ILogger logger) { - if (fileProvider == null) - { - throw new ArgumentNullException(nameof(fileProvider)); - } - - if (projectEngine == null) - { - throw new ArgumentNullException(nameof(projectEngine)); - } - - if (csharpCompiler == null) - { - throw new ArgumentNullException(nameof(csharpCompiler)); - } - - if (precompiledViews == null) - { - throw new ArgumentNullException(nameof(precompiledViews)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(fileProvider); + ArgumentNullException.ThrowIfNull(projectEngine); + ArgumentNullException.ThrowIfNull(csharpCompiler); + ArgumentNullException.ThrowIfNull(precompiledViews); + ArgumentNullException.ThrowIfNull(logger); _fileProvider = fileProvider; _projectEngine = projectEngine; @@ -103,10 +84,7 @@ public RuntimeViewCompiler( public Task CompileAsync(string relativePath) { - if (relativePath == null) - { - throw new ArgumentNullException(nameof(relativePath)); - } + ArgumentNullException.ThrowIfNull(relativePath); // Attempt to lookup the cache entry using the passed in path. This will succeed if the path is already // normalized and a cache entry exists. diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/test/TestInfrastructure/VirtualRazorProjectFileSystem.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/test/TestInfrastructure/VirtualRazorProjectFileSystem.cs index 4df10f11a77e..963fcd79e7ca 100644 --- a/src/Mvc/Mvc.Razor.RuntimeCompilation/test/TestInfrastructure/VirtualRazorProjectFileSystem.cs +++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/test/TestInfrastructure/VirtualRazorProjectFileSystem.cs @@ -30,10 +30,7 @@ public override RazorProjectItem GetItem(string path, string fileKind) public void Add(RazorProjectItem projectItem) { - if (projectItem == null) - { - throw new ArgumentNullException(nameof(projectItem)); - } + ArgumentNullException.ThrowIfNull(projectItem); var filePath = NormalizeAndEnsureValidPath(projectItem.FilePath); _root.AddFile(new FileNode(filePath, projectItem)); diff --git a/src/Mvc/Mvc.Razor/src/ApplicationParts/CompiledRazorAssemblyApplicationPartFactory.cs b/src/Mvc/Mvc.Razor/src/ApplicationParts/CompiledRazorAssemblyApplicationPartFactory.cs index 5923cd596c14..a364482bb640 100644 --- a/src/Mvc/Mvc.Razor/src/ApplicationParts/CompiledRazorAssemblyApplicationPartFactory.cs +++ b/src/Mvc/Mvc.Razor/src/ApplicationParts/CompiledRazorAssemblyApplicationPartFactory.cs @@ -20,10 +20,7 @@ public class CompiledRazorAssemblyApplicationPartFactory : ApplicationPartFactor /// The sequence of instances. public static IEnumerable GetDefaultApplicationParts(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); yield return new CompiledRazorAssemblyPart(assembly); } diff --git a/src/Mvc/Mvc.Razor/src/Compilation/CompiledViewDescriptor.cs b/src/Mvc/Mvc.Razor/src/Compilation/CompiledViewDescriptor.cs index a920bdfcdde9..711460d662b8 100644 --- a/src/Mvc/Mvc.Razor/src/Compilation/CompiledViewDescriptor.cs +++ b/src/Mvc/Mvc.Razor/src/Compilation/CompiledViewDescriptor.cs @@ -24,10 +24,7 @@ public CompiledViewDescriptor() /// The . public CompiledViewDescriptor(RazorCompiledItem item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); Item = item; RelativePath = ViewPath.NormalizePath(item.Identifier); diff --git a/src/Mvc/Mvc.Razor/src/Compilation/DefaultRazorPageFactoryProvider.cs b/src/Mvc/Mvc.Razor/src/Compilation/DefaultRazorPageFactoryProvider.cs index 1fc5dfa2b6d4..05b69899c02d 100644 --- a/src/Mvc/Mvc.Razor/src/Compilation/DefaultRazorPageFactoryProvider.cs +++ b/src/Mvc/Mvc.Razor/src/Compilation/DefaultRazorPageFactoryProvider.cs @@ -27,10 +27,7 @@ public DefaultRazorPageFactoryProvider(IViewCompilerProvider viewCompilerProvide /// public RazorPageFactoryResult CreateFactory(string relativePath) { - if (relativePath == null) - { - throw new ArgumentNullException(nameof(relativePath)); - } + ArgumentNullException.ThrowIfNull(relativePath); if (relativePath.StartsWith("~/", StringComparison.Ordinal)) { diff --git a/src/Mvc/Mvc.Razor/src/Compilation/DefaultViewCompiler.cs b/src/Mvc/Mvc.Razor/src/Compilation/DefaultViewCompiler.cs index 7b19aa7b6305..162da5dfaad6 100644 --- a/src/Mvc/Mvc.Razor/src/Compilation/DefaultViewCompiler.cs +++ b/src/Mvc/Mvc.Razor/src/Compilation/DefaultViewCompiler.cs @@ -87,10 +87,7 @@ internal void ClearCache() /// public Task CompileAsync(string relativePath) { - if (relativePath == null) - { - throw new ArgumentNullException(nameof(relativePath)); - } + ArgumentNullException.ThrowIfNull(relativePath); EnsureCompiledViews(_logger); diff --git a/src/Mvc/Mvc.Razor/src/DefaultTagHelperFactory.cs b/src/Mvc/Mvc.Razor/src/DefaultTagHelperFactory.cs index 86faae32c156..7f659efb6d33 100644 --- a/src/Mvc/Mvc.Razor/src/DefaultTagHelperFactory.cs +++ b/src/Mvc/Mvc.Razor/src/DefaultTagHelperFactory.cs @@ -29,10 +29,7 @@ internal sealed class DefaultTagHelperFactory : ITagHelperFactory /// public DefaultTagHelperFactory(ITagHelperActivator activator) { - if (activator == null) - { - throw new ArgumentNullException(nameof(activator)); - } + ArgumentNullException.ThrowIfNull(activator); _activator = activator; _injectActions = new ConcurrentDictionary[]>(); @@ -52,10 +49,7 @@ internal void ClearCache() public TTagHelper CreateTagHelper(ViewContext context) where TTagHelper : ITagHelper { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var tagHelper = _activator.Create(context); diff --git a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcBuilderExtensions.cs b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcBuilderExtensions.cs index 8c42faa73949..a0a0a56d99d6 100644 --- a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcBuilderExtensions.cs @@ -22,15 +22,8 @@ public static IMvcBuilder AddRazorOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -44,10 +37,7 @@ public static IMvcBuilder AddRazorOptions( /// The instance this method extends. public static IMvcBuilder AddTagHelpersAsServices(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); TagHelpersAsServices.AddTagHelpersAsServices(builder.PartManager, builder.Services); return builder; @@ -69,15 +59,8 @@ public static IMvcBuilder InitializeTagHelper( Action initialize) where TTagHelper : ITagHelper { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (initialize == null) - { - throw new ArgumentNullException(nameof(initialize)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(initialize); var initializer = new TagHelperInitializer(initialize); diff --git a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcCoreBuilderExtensions.cs index 0f2d46d0ac8f..3b2c9667687b 100644 --- a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcCoreBuilderExtensions.cs @@ -30,10 +30,7 @@ public static class MvcRazorMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddRazorViewEngine(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AddViews(); AddRazorViewEngineFeatureProviders(builder.PartManager); @@ -51,15 +48,8 @@ public static IMvcCoreBuilder AddRazorViewEngine( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.AddViews(); @@ -92,10 +82,7 @@ internal static void AddRazorViewEngineFeatureProviders(ApplicationPartManager p /// The instance this method extends. public static IMvcCoreBuilder AddTagHelpersAsServices(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); TagHelpersAsServices.AddTagHelpersAsServices(builder.PartManager, builder.Services); return builder; @@ -117,15 +104,8 @@ public static IMvcCoreBuilder InitializeTagHelper( Action initialize) where TTagHelper : ITagHelper { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (initialize == null) - { - throw new ArgumentNullException(nameof(initialize)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(initialize); var initializer = new TagHelperInitializer(initialize); diff --git a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcViewOptionsSetup.cs b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcViewOptionsSetup.cs index c98c4f4560ec..b6bbbf1b51c6 100644 --- a/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcViewOptionsSetup.cs +++ b/src/Mvc/Mvc.Razor/src/DependencyInjection/MvcRazorMvcViewOptionsSetup.cs @@ -20,10 +20,7 @@ internal sealed class MvcRazorMvcViewOptionsSetup : IConfigureOptionsThe . public MvcRazorMvcViewOptionsSetup(IRazorViewEngine razorViewEngine) { - if (razorViewEngine == null) - { - throw new ArgumentNullException(nameof(razorViewEngine)); - } + ArgumentNullException.ThrowIfNull(razorViewEngine); _razorViewEngine = razorViewEngine; } @@ -34,10 +31,7 @@ public MvcRazorMvcViewOptionsSetup(IRazorViewEngine razorViewEngine) /// The to configure. public void Configure(MvcViewOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.ViewEngines.Add(_razorViewEngine); } diff --git a/src/Mvc/Mvc.Razor/src/DependencyInjection/TagHelpersAsServices.cs b/src/Mvc/Mvc.Razor/src/DependencyInjection/TagHelpersAsServices.cs index a426604d55e3..5b94a420d46c 100644 --- a/src/Mvc/Mvc.Razor/src/DependencyInjection/TagHelpersAsServices.cs +++ b/src/Mvc/Mvc.Razor/src/DependencyInjection/TagHelpersAsServices.cs @@ -13,15 +13,8 @@ internal static class TagHelpersAsServices { public static void AddTagHelpersAsServices(ApplicationPartManager manager, IServiceCollection services) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } - - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(manager); + ArgumentNullException.ThrowIfNull(services); var feature = new TagHelperFeature(); manager.PopulateFeature(feature); diff --git a/src/Mvc/Mvc.Razor/src/HelperResult.cs b/src/Mvc/Mvc.Razor/src/HelperResult.cs index cf44694fe954..f4e0965c2b37 100644 --- a/src/Mvc/Mvc.Razor/src/HelperResult.cs +++ b/src/Mvc/Mvc.Razor/src/HelperResult.cs @@ -22,10 +22,7 @@ public class HelperResult : IHtmlContent /// . public HelperResult(Func asyncAction) { - if (asyncAction == null) - { - throw new ArgumentNullException(nameof(asyncAction)); - } + ArgumentNullException.ThrowIfNull(asyncAction); _asyncAction = asyncAction; } @@ -42,15 +39,8 @@ public HelperResult(Func asyncAction) /// The to encode the content. public virtual void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); _asyncAction(writer).GetAwaiter().GetResult(); } diff --git a/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultFileVersionProvider.cs b/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultFileVersionProvider.cs index 54f59e66797b..dfb91d29a711 100644 --- a/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultFileVersionProvider.cs +++ b/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultFileVersionProvider.cs @@ -22,15 +22,8 @@ public DefaultFileVersionProvider( IWebHostEnvironment hostingEnvironment, TagHelperMemoryCacheProvider cacheProvider) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - - if (cacheProvider == null) - { - throw new ArgumentNullException(nameof(cacheProvider)); - } + ArgumentNullException.ThrowIfNull(hostingEnvironment); + ArgumentNullException.ThrowIfNull(cacheProvider); FileProvider = hostingEnvironment.WebRootFileProvider; Cache = cacheProvider.Cache; @@ -42,10 +35,7 @@ public DefaultFileVersionProvider( public string AddFileVersionToPath(PathString requestPathBase, string path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); var resolvedPath = path; diff --git a/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultTagHelperActivator.cs b/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultTagHelperActivator.cs index dac3a77944eb..150a2b363752 100644 --- a/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultTagHelperActivator.cs +++ b/src/Mvc/Mvc.Razor/src/Infrastructure/DefaultTagHelperActivator.cs @@ -16,10 +16,7 @@ internal sealed class DefaultTagHelperActivator : ITagHelperActivator public TTagHelper Create(ViewContext context) where TTagHelper : ITagHelper { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return Cache.Create(context.HttpContext.RequestServices); } diff --git a/src/Mvc/Mvc.Razor/src/LanguageViewLocationExpander.cs b/src/Mvc/Mvc.Razor/src/LanguageViewLocationExpander.cs index 0385eb055acc..676e256fbe81 100644 --- a/src/Mvc/Mvc.Razor/src/LanguageViewLocationExpander.cs +++ b/src/Mvc/Mvc.Razor/src/LanguageViewLocationExpander.cs @@ -42,10 +42,7 @@ public LanguageViewLocationExpander(LanguageViewLocationExpanderFormat format) /// public void PopulateValues(ViewLocationExpanderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Using CurrentUICulture so it loads the locale specific resources for the views. context.Values[ValueKey] = CultureInfo.CurrentUICulture.Name; @@ -56,15 +53,8 @@ public virtual IEnumerable ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable viewLocations) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (viewLocations == null) - { - throw new ArgumentNullException(nameof(viewLocations)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(viewLocations); context.Values.TryGetValue(ValueKey, out var value); diff --git a/src/Mvc/Mvc.Razor/src/RazorPage.cs b/src/Mvc/Mvc.Razor/src/RazorPage.cs index 00c202f1314b..aca0ed5825bf 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPage.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPage.cs @@ -54,15 +54,8 @@ public void IgnoreBody() /// The to execute when rendering the section. public override void DefineSection(string name, RenderAsyncDelegate section) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (section == null) - { - throw new ArgumentNullException(nameof(section)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(section); if (SectionWriters.ContainsKey(name)) { @@ -78,10 +71,7 @@ public override void DefineSection(string name, RenderAsyncDelegate section) /// true if the specified section is defined in the content page; otherwise, false. public bool IsSectionDefined(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); EnsureMethodCanBeInvoked(nameof(IsSectionDefined)); return PreviousSectionWriters.ContainsKey(name); @@ -97,10 +87,7 @@ public bool IsSectionDefined(string name) /// value does not represent the rendered content. public HtmlString? RenderSection(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return RenderSection(name, required: true); } @@ -116,10 +103,7 @@ public bool IsSectionDefined(string name) /// value does not represent the rendered content. public HtmlString? RenderSection(string name, bool required) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); EnsureMethodCanBeInvoked(nameof(RenderSection)); @@ -139,10 +123,7 @@ public bool IsSectionDefined(string name) /// value does not represent the rendered content. public Task RenderSectionAsync(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); return RenderSectionAsync(name, required: true); } @@ -163,10 +144,7 @@ public bool IsSectionDefined(string name) /// was not registered using the @section in the Razor page. public Task RenderSectionAsync(string name, bool required) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); EnsureMethodCanBeInvoked(nameof(RenderSectionAsync)); return RenderSectionAsyncCore(name, required); @@ -213,10 +191,7 @@ public bool IsSectionDefined(string name) /// The section to ignore. public void IgnoreSection(string sectionName) { - if (sectionName == null) - { - throw new ArgumentNullException(nameof(sectionName)); - } + ArgumentNullException.ThrowIfNull(sectionName); if (PreviousSectionWriters.ContainsKey(sectionName)) { diff --git a/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs b/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs index 9e28ac1aa412..c6ab1dde933f 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPageActivator.cs @@ -57,15 +57,8 @@ internal void ClearCache() /// public void Activate(IRazorPage page, ViewContext context) { - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(page); + ArgumentNullException.ThrowIfNull(context); var propertyActivator = GetOrAddCacheEntry(page); propertyActivator.Activate(page, context); diff --git a/src/Mvc/Mvc.Razor/src/RazorPageBase.cs b/src/Mvc/Mvc.Razor/src/RazorPageBase.cs index 48f64937b4b3..07a187d48fd4 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPageBase.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPageBase.cs @@ -285,10 +285,7 @@ public string EndWriteTagHelperAttribute() // Internal for unit testing. protected internal virtual void PushWriter(TextWriter writer) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); var viewContext = ViewContext; _textWriterStack.Push(viewContext.Writer); @@ -315,10 +312,7 @@ protected internal virtual TextWriter PopWriter() /// The href for the contentPath. public virtual string Href(string contentPath) { - if (contentPath == null) - { - throw new ArgumentNullException(nameof(contentPath)); - } + ArgumentNullException.ThrowIfNull(contentPath); if (_urlHelper == null) { @@ -350,15 +344,8 @@ protected void DefineSection(string name, Func section) /// The to execute when rendering the section. public virtual void DefineSection(string name, RenderAsyncDelegate section) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (section == null) - { - throw new ArgumentNullException(nameof(section)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(section); if (SectionWriters.ContainsKey(name)) { @@ -467,15 +454,8 @@ public virtual void BeginWriteAttribute( int suffixOffset, int attributeValuesCount) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - - if (suffix == null) - { - throw new ArgumentNullException(nameof(suffix)); - } + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(suffix); _attributeInfo = new AttributeInfo(name, prefix, prefixOffset, suffix, suffixOffset, attributeValuesCount); diff --git a/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs b/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs index c4062bcb6791..0347e01dde66 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPagePropertyActivator.cs @@ -45,10 +45,7 @@ public RazorPagePropertyActivator( public void Activate(object page, ViewContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); context.ViewData = CreateViewDataDictionary(context); for (var i = 0; i < _propertyActivators.Length; i++) diff --git a/src/Mvc/Mvc.Razor/src/RazorPageResult.cs b/src/Mvc/Mvc.Razor/src/RazorPageResult.cs index 5108ec68fe4a..cea70797d999 100644 --- a/src/Mvc/Mvc.Razor/src/RazorPageResult.cs +++ b/src/Mvc/Mvc.Razor/src/RazorPageResult.cs @@ -15,15 +15,8 @@ public readonly struct RazorPageResult /// The located . public RazorPageResult(string name, IRazorPage page) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(page); Name = name; Page = page; @@ -37,15 +30,8 @@ public RazorPageResult(string name, IRazorPage page) /// The locations that were searched. public RazorPageResult(string name, IEnumerable searchedLocations) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (searchedLocations == null) - { - throw new ArgumentNullException(nameof(searchedLocations)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(searchedLocations); Name = name; Page = null; diff --git a/src/Mvc/Mvc.Razor/src/RazorView.cs b/src/Mvc/Mvc.Razor/src/RazorView.cs index 8094fce1e6d7..261630f740c0 100644 --- a/src/Mvc/Mvc.Razor/src/RazorView.cs +++ b/src/Mvc/Mvc.Razor/src/RazorView.cs @@ -41,35 +41,12 @@ public RazorView( HtmlEncoder htmlEncoder, DiagnosticListener diagnosticListener) { - if (viewEngine == null) - { - throw new ArgumentNullException(nameof(viewEngine)); - } - - if (pageActivator == null) - { - throw new ArgumentNullException(nameof(pageActivator)); - } - - if (viewStartPages == null) - { - throw new ArgumentNullException(nameof(viewStartPages)); - } - - if (razorPage == null) - { - throw new ArgumentNullException(nameof(razorPage)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (diagnosticListener == null) - { - throw new ArgumentNullException(nameof(diagnosticListener)); - } + ArgumentNullException.ThrowIfNull(viewEngine); + ArgumentNullException.ThrowIfNull(pageActivator); + ArgumentNullException.ThrowIfNull(viewStartPages); + ArgumentNullException.ThrowIfNull(razorPage); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(diagnosticListener); _viewEngine = viewEngine; _pageActivator = pageActivator; @@ -97,10 +74,7 @@ public RazorView( /// public virtual async Task RenderAsync(ViewContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // This GetRequiredService call is by design. ViewBufferScope is a scoped service, RazorViewEngine // is the component responsible for creating RazorViews and it is a Singleton service. It doesn't diff --git a/src/Mvc/Mvc.Razor/src/RazorViewEngine.cs b/src/Mvc/Mvc.Razor/src/RazorViewEngine.cs index a4d5fbbc688b..30248a577bfd 100644 --- a/src/Mvc/Mvc.Razor/src/RazorViewEngine.cs +++ b/src/Mvc/Mvc.Razor/src/RazorViewEngine.cs @@ -106,10 +106,7 @@ internal void ClearCache() /// public RazorPageResult FindPage(ActionContext context, string pageName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (string.IsNullOrEmpty(pageName)) { @@ -163,10 +160,7 @@ public RazorPageResult GetPage(string executingFilePath, string pagePath) /// public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (string.IsNullOrEmpty(viewName)) { diff --git a/src/Mvc/Mvc.Razor/src/RazorViewEngineOptionsSetup.cs b/src/Mvc/Mvc.Razor/src/RazorViewEngineOptionsSetup.cs index 98d8d757679e..d5ecf37d1da7 100644 --- a/src/Mvc/Mvc.Razor/src/RazorViewEngineOptionsSetup.cs +++ b/src/Mvc/Mvc.Razor/src/RazorViewEngineOptionsSetup.cs @@ -9,10 +9,7 @@ internal sealed class RazorViewEngineOptionsSetup : IConfigureOptions public TTagHelper Create(ViewContext context) where TTagHelper : ITagHelper { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return context.HttpContext.RequestServices.GetRequiredService(); } diff --git a/src/Mvc/Mvc.Razor/src/TagHelperComponentManager.cs b/src/Mvc/Mvc.Razor/src/TagHelperComponentManager.cs index a115c508f99f..4f82cdab1199 100644 --- a/src/Mvc/Mvc.Razor/src/TagHelperComponentManager.cs +++ b/src/Mvc/Mvc.Razor/src/TagHelperComponentManager.cs @@ -17,10 +17,7 @@ internal sealed class TagHelperComponentManager : ITagHelperComponentManager /// The collection of s. public TagHelperComponentManager(IEnumerable tagHelperComponents) { - if (tagHelperComponents == null) - { - throw new ArgumentNullException(nameof(tagHelperComponents)); - } + ArgumentNullException.ThrowIfNull(tagHelperComponents); Components = new List(tagHelperComponents); } diff --git a/src/Mvc/Mvc.Razor/src/TagHelperInitializerOfT.cs b/src/Mvc/Mvc.Razor/src/TagHelperInitializerOfT.cs index 3e948ec6240b..9d55c4f13d4b 100644 --- a/src/Mvc/Mvc.Razor/src/TagHelperInitializerOfT.cs +++ b/src/Mvc/Mvc.Razor/src/TagHelperInitializerOfT.cs @@ -18,10 +18,7 @@ public class TagHelperInitializer : ITagHelperInitializerThe initialization delegate. public TagHelperInitializer(Action action) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); _initializeDelegate = action; } @@ -34,10 +31,7 @@ public void Initialize(TTagHelper helper, ViewContext context) throw new ArgumentNullException(nameof(helper)); } - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _initializeDelegate(helper, context); } diff --git a/src/Mvc/Mvc.Razor/src/ViewLocationCacheResult.cs b/src/Mvc/Mvc.Razor/src/ViewLocationCacheResult.cs index 94922c99f9d2..ee4fb51e1af4 100644 --- a/src/Mvc/Mvc.Razor/src/ViewLocationCacheResult.cs +++ b/src/Mvc/Mvc.Razor/src/ViewLocationCacheResult.cs @@ -18,10 +18,7 @@ public ViewLocationCacheResult( ViewLocationCacheItem view, IReadOnlyList viewStarts) { - if (viewStarts == null) - { - throw new ArgumentNullException(nameof(viewStarts)); - } + ArgumentNullException.ThrowIfNull(viewStarts); ViewEntry = view; ViewStartEntries = viewStarts; @@ -35,10 +32,7 @@ public ViewLocationCacheResult( /// Locations that were searched. public ViewLocationCacheResult(IEnumerable searchedLocations) { - if (searchedLocations == null) - { - throw new ArgumentNullException(nameof(searchedLocations)); - } + ArgumentNullException.ThrowIfNull(searchedLocations); SearchedLocations = searchedLocations; } diff --git a/src/Mvc/Mvc.Razor/src/ViewLocationExpanderContext.cs b/src/Mvc/Mvc.Razor/src/ViewLocationExpanderContext.cs index e83e90ab7da9..8c63aa187eae 100644 --- a/src/Mvc/Mvc.Razor/src/ViewLocationExpanderContext.cs +++ b/src/Mvc/Mvc.Razor/src/ViewLocationExpanderContext.cs @@ -25,15 +25,8 @@ public ViewLocationExpanderContext( string? pageName, bool isMainPage) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (viewName == null) - { - throw new ArgumentNullException(nameof(viewName)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(viewName); ActionContext = actionContext; ViewName = viewName; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AuthorizationPageApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AuthorizationPageApplicationModelProvider.cs index ab30e37b1cd7..eccb102954cb 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AuthorizationPageApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AuthorizationPageApplicationModelProvider.cs @@ -26,10 +26,7 @@ public AuthorizationPageApplicationModelProvider( public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (_mvcOptions.EnableEndpointRouting) { diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AutoValidateAntiforgeryPageApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AutoValidateAntiforgeryPageApplicationModelProvider.cs index 6dce65edebd4..217f0e619770 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AutoValidateAntiforgeryPageApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/AutoValidateAntiforgeryPageApplicationModelProvider.cs @@ -17,10 +17,7 @@ public void OnProvidersExecuted(PageApplicationModelProviderContext context) public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var pageApplicationModel = context.PageApplicationModel; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs index 6d89bdc26fcc..f37834aa8255 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/CompiledPageRouteModelProvider.cs @@ -35,28 +35,19 @@ public CompiledPageRouteModelProvider( public void OnProvidersExecuting(PageRouteModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); CreateModels(context); } public void OnProvidersExecuted(PageRouteModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); } private IEnumerable GetViewDescriptors(ApplicationPartManager applicationManager) { - if (applicationManager == null) - { - throw new ArgumentNullException(nameof(applicationManager)); - } + ArgumentNullException.ThrowIfNull(applicationManager); var viewsFeature = GetViewFeature(applicationManager); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelPartsProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelPartsProvider.cs index 1e98ca08516c..5de6835aefa6 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelPartsProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelPartsProvider.cs @@ -32,10 +32,7 @@ public DefaultPageApplicationModelPartsProvider(IModelMetadataProvider modelMeta /// The . public PageHandlerModel? CreateHandlerModel(MethodInfo method) { - if (method == null) - { - throw new ArgumentNullException(nameof(method)); - } + ArgumentNullException.ThrowIfNull(method); if (!IsHandler(method)) { @@ -77,10 +74,7 @@ public DefaultPageApplicationModelPartsProvider(IModelMetadataProvider modelMeta /// The . public PageParameterModel CreateParameterModel(ParameterInfo parameter) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } + ArgumentNullException.ThrowIfNull(parameter); var attributes = parameter.GetCustomAttributes(inherit: true); @@ -109,10 +103,7 @@ public PageParameterModel CreateParameterModel(ParameterInfo parameter) /// The . public PagePropertyModel CreatePropertyModel(PropertyInfo property) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } + ArgumentNullException.ThrowIfNull(property); var propertyAttributes = property.GetCustomAttributes(inherit: true); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelProvider.cs index c217a6b2ed69..ce3d90e9a4a1 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/DefaultPageApplicationModelProvider.cs @@ -41,10 +41,7 @@ public DefaultPageApplicationModelProvider( /// public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); context.PageApplicationModel = CreateModel(context.ActionDescriptor, context.PageType); } @@ -64,15 +61,8 @@ private PageApplicationModel CreateModel( PageActionDescriptor actionDescriptor, TypeInfo pageTypeInfo) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } - - if (pageTypeInfo == null) - { - throw new ArgumentNullException(nameof(pageTypeInfo)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); + ArgumentNullException.ThrowIfNull(pageTypeInfo); if (!typeof(PageBase).GetTypeInfo().IsAssignableFrom(pageTypeInfo)) { diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageApplicationModel.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageApplicationModel.cs index 17154e19a90c..a3828c2fb0e4 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageApplicationModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageApplicationModel.cs @@ -54,10 +54,7 @@ public PageApplicationModel( /// The to copy from. public PageApplicationModel(PageApplicationModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); ActionDescriptor = other.ActionDescriptor; HandlerType = other.HandlerType; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageConventionCollection.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageConventionCollection.cs index 978f324c10a8..9fdb704d1289 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageConventionCollection.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageConventionCollection.cs @@ -62,10 +62,7 @@ public IPageApplicationModelConvention AddPageApplicationModelConvention( { EnsureValidPageName(pageName); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new PageApplicationModelConvention(pageName, action)); } @@ -96,10 +93,7 @@ public IPageApplicationModelConvention AddAreaPageApplicationModelConvention( EnsureValidPageName(pageName); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new PageApplicationModelConvention(areaName, pageName, action)); } @@ -115,10 +109,7 @@ public IPageApplicationModelConvention AddFolderApplicationModelConvention(strin { EnsureValidFolderPath(folderPath); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new FolderApplicationModelConvention(folderPath, action)); } @@ -149,10 +140,7 @@ public IPageApplicationModelConvention AddAreaFolderApplicationModelConvention( EnsureValidFolderPath(folderPath); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new FolderApplicationModelConvention(areaName, folderPath, action)); } @@ -168,10 +156,7 @@ public IPageRouteModelConvention AddPageRouteModelConvention(string pageName, Ac { EnsureValidPageName(pageName); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new PageRouteModelConvention(pageName, action)); } @@ -199,10 +184,7 @@ public IPageRouteModelConvention AddAreaPageRouteModelConvention(string areaName EnsureValidPageName(pageName); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new PageRouteModelConvention(areaName, pageName, action)); } @@ -218,10 +200,7 @@ public IPageRouteModelConvention AddFolderRouteModelConvention(string folderPath { EnsureValidFolderPath(folderPath); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new FolderRouteModelConvention(folderPath, action)); } @@ -249,10 +228,7 @@ public IPageRouteModelConvention AddAreaFolderRouteModelConvention(string areaNa EnsureValidFolderPath(folderPath); - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } + ArgumentNullException.ThrowIfNull(action); return Add(new FolderRouteModelConvention(areaName, folderPath, action)); } diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageHandlerModel.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageHandlerModel.cs index 8b81e7e8e1a7..b7e27487240d 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageHandlerModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageHandlerModel.cs @@ -35,10 +35,7 @@ public PageHandlerModel( /// The which needs to be copied. public PageHandlerModel(PageHandlerModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); MethodInfo = other.MethodInfo; HandlerName = other.HandlerName; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageParameterModel.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageParameterModel.cs index efc3bd422726..7eed3e6214d0 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageParameterModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageParameterModel.cs @@ -22,15 +22,8 @@ public PageParameterModel( IReadOnlyList attributes) : base(parameterInfo.ParameterType, attributes) { - if (parameterInfo == null) - { - throw new ArgumentNullException(nameof(parameterInfo)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(parameterInfo); + ArgumentNullException.ThrowIfNull(attributes); ParameterInfo = parameterInfo; } @@ -42,10 +35,7 @@ public PageParameterModel( public PageParameterModel(PageParameterModel other) : base(other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Handler = other.Handler; ParameterInfo = other.ParameterInfo; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PagePropertyModel.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PagePropertyModel.cs index 6ed10dc0441f..29ddd5a8bd23 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PagePropertyModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PagePropertyModel.cs @@ -33,10 +33,7 @@ public PagePropertyModel( public PagePropertyModel(PagePropertyModel other) : base(other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); Page = other.Page; BindingInfo = other.BindingInfo == null ? null : new BindingInfo(other.BindingInfo); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModel.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModel.cs index 5c0062ec4e24..754440f96f8c 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteModel.cs @@ -45,10 +45,7 @@ public PageRouteModel(string relativePath, string viewEnginePath, string? areaNa /// The to copy from. public PageRouteModel(PageRouteModel other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); RelativePath = other.RelativePath; ViewEnginePath = other.ViewEnginePath; diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs index 83dda2c21af7..2eadaac416f0 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs @@ -20,10 +20,7 @@ public class PageRouteTransformerConvention : IPageRouteModelConvention /// The to use resolve page routes. public PageRouteTransformerConvention(IOutboundParameterTransformer parameterTransformer) { - if (parameterTransformer == null) - { - throw new ArgumentNullException(nameof(parameterTransformer)); - } + ArgumentNullException.ThrowIfNull(parameterTransformer); _parameterTransformer = parameterTransformer; } diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ResponseCacheFilterApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ResponseCacheFilterApplicationModelProvider.cs index 1b54d7dae38f..8ed2e8aaa318 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ResponseCacheFilterApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ResponseCacheFilterApplicationModelProvider.cs @@ -15,10 +15,7 @@ internal sealed class ResponseCacheFilterApplicationModelProvider : IPageApplica public ResponseCacheFilterApplicationModelProvider(IOptions mvcOptionsAccessor, ILoggerFactory loggerFactory) { - if (mvcOptionsAccessor == null) - { - throw new ArgumentNullException(nameof(mvcOptionsAccessor)); - } + ArgumentNullException.ThrowIfNull(mvcOptionsAccessor); _mvcOptions = mvcOptionsAccessor.Value; _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); @@ -29,10 +26,7 @@ public ResponseCacheFilterApplicationModelProvider(IOptions mvcOptio public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var pageModel = context.PageApplicationModel; var responseCacheAttributes = pageModel.HandlerTypeAttributes.OfType(); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/TempDataFilterPageApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/TempDataFilterPageApplicationModelProvider.cs index 0ec338253ca7..6df097443602 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/TempDataFilterPageApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/TempDataFilterPageApplicationModelProvider.cs @@ -25,10 +25,7 @@ public void OnProvidersExecuted(PageApplicationModelProviderContext context) public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var pageApplicationModel = context.PageApplicationModel; var handlerType = pageApplicationModel.HandlerType.AsType(); diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ViewDataAttributePageApplicationModelProvider.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ViewDataAttributePageApplicationModelProvider.cs index 4b54a1af732b..34e4e46566bc 100644 --- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ViewDataAttributePageApplicationModelProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/ViewDataAttributePageApplicationModelProvider.cs @@ -20,10 +20,7 @@ public void OnProvidersExecuted(PageApplicationModelProviderContext context) /// public void OnProvidersExecuting(PageApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var handlerType = context.PageApplicationModel.HandlerType.AsType(); diff --git a/src/Mvc/Mvc.RazorPages/src/Builder/PageActionEndpointConventionBuilder.cs b/src/Mvc/Mvc.RazorPages/src/Builder/PageActionEndpointConventionBuilder.cs index a60499c6fb98..cdc7b82fdb0d 100644 --- a/src/Mvc/Mvc.RazorPages/src/Builder/PageActionEndpointConventionBuilder.cs +++ b/src/Mvc/Mvc.RazorPages/src/Builder/PageActionEndpointConventionBuilder.cs @@ -29,10 +29,7 @@ internal PageActionEndpointConventionBuilder(object @lock, ListThe convention to add to the builder. public void Add(Action convention) { - if (convention == null) - { - throw new ArgumentNullException(nameof(convention)); - } + ArgumentNullException.ThrowIfNull(convention); // The lock is shared with the data source. We want to lock here // to avoid mutating this list while its read in the data source. diff --git a/src/Mvc/Mvc.RazorPages/src/Builder/RazorPagesEndpointRouteBuilderExtensions.cs b/src/Mvc/Mvc.RazorPages/src/Builder/RazorPagesEndpointRouteBuilderExtensions.cs index 5e34a2d4e012..a5d579105888 100644 --- a/src/Mvc/Mvc.RazorPages/src/Builder/RazorPagesEndpointRouteBuilderExtensions.cs +++ b/src/Mvc/Mvc.RazorPages/src/Builder/RazorPagesEndpointRouteBuilderExtensions.cs @@ -24,10 +24,7 @@ public static class RazorPagesEndpointRouteBuilderExtensions /// An for endpoints associated with Razor Pages. public static PageActionEndpointConventionBuilder MapRazorPages(this IEndpointRouteBuilder endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); EnsureRazorPagesServices(endpoints); @@ -60,15 +57,8 @@ public static PageActionEndpointConventionBuilder MapRazorPages(this IEndpointRo /// public static IEndpointConventionBuilder MapFallbackToPage(this IEndpointRouteBuilder endpoints, string page) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(page); PageConventionCollection.EnsureValidPageName(page, nameof(page)); @@ -124,20 +114,9 @@ public static IEndpointConventionBuilder MapFallbackToPage( [StringSyntax("Route")] string pattern, string page) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(page); PageConventionCollection.EnsureValidPageName(page, nameof(page)); @@ -190,15 +169,8 @@ public static IEndpointConventionBuilder MapFallbackToAreaPage( string page, string area) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(page); PageConventionCollection.EnsureValidPageName(page, nameof(page)); @@ -256,20 +228,9 @@ public static IEndpointConventionBuilder MapFallbackToAreaPage( string page, string area) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(page); PageConventionCollection.EnsureValidPageName(page, nameof(page)); @@ -336,15 +297,8 @@ public static void MapDynamicPageRoute(this IEndpointRouteBuilder public static void MapDynamicPageRoute(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, object? state) where TTransformer : DynamicRouteValueTransformer { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); EnsureRazorPagesServices(endpoints); @@ -377,15 +331,8 @@ public static void MapDynamicPageRoute(this IEndpointRouteBuilder public static void MapDynamicPageRoute(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, object state, int order) where TTransformer : DynamicRouteValueTransformer { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } - - if (pattern == null) - { - throw new ArgumentNullException(nameof(pattern)); - } + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(pattern); EnsureRazorPagesServices(endpoints); diff --git a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcBuilderExtensions.cs b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcBuilderExtensions.cs index 2fcbbae6b2ac..f6841aeb8338 100644 --- a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcBuilderExtensions.cs @@ -22,15 +22,8 @@ public static IMvcBuilder AddRazorPagesOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -44,10 +37,7 @@ public static IMvcBuilder AddRazorPagesOptions( /// The . public static IMvcBuilder WithRazorPagesRoot(this IMvcBuilder builder, string rootDirectory) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); if (string.IsNullOrEmpty(rootDirectory)) { @@ -70,10 +60,7 @@ public static IMvcBuilder WithRazorPagesRoot(this IMvcBuilder builder, string ro /// The . public static IMvcBuilder WithRazorPagesAtContentRoot(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.Services.Configure(options => options.RootDirectory = "/"); return builder; diff --git a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs index 36caf26e487f..9537cdd8b7a3 100644 --- a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/MvcRazorPagesMvcCoreBuilderExtensions.cs @@ -28,10 +28,7 @@ public static class MvcRazorPagesMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddRazorPages(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AddRazorViewEngine(); @@ -50,15 +47,8 @@ public static IMvcCoreBuilder AddRazorPages( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.AddRazorViewEngine(); @@ -77,10 +67,7 @@ public static IMvcCoreBuilder AddRazorPages( /// public static IMvcCoreBuilder WithRazorPagesRoot(this IMvcCoreBuilder builder, string rootDirectory) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); if (string.IsNullOrEmpty(rootDirectory)) { diff --git a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/PageConventionCollectionExtensions.cs b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/PageConventionCollectionExtensions.cs index 231b99586f63..8d969526a77d 100644 --- a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/PageConventionCollectionExtensions.cs +++ b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/PageConventionCollectionExtensions.cs @@ -25,15 +25,8 @@ public static IPageApplicationModelConvention ConfigureFilter( this PageConventionCollection conventions, Func factory) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(factory); return conventions.AddFolderApplicationModelConvention("/", model => model.Filters.Add(factory(model))); } @@ -46,15 +39,8 @@ public static IPageApplicationModelConvention ConfigureFilter( /// The . public static PageConventionCollection ConfigureFilter(this PageConventionCollection conventions, IFilterMetadata filter) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (filter == null) - { - throw new ArgumentNullException(nameof(filter)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(filter); conventions.AddFolderApplicationModelConvention("/", model => model.Filters.Add(filter)); return conventions; @@ -69,15 +55,8 @@ public static PageConventionCollection ConfigureFilter(this PageConventionCollec /// The . public static PageConventionCollection Add(this PageConventionCollection conventions, IParameterModelBaseConvention convention) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } - - if (convention == null) - { - throw new ArgumentNullException(nameof(convention)); - } + ArgumentNullException.ThrowIfNull(conventions); + ArgumentNullException.ThrowIfNull(convention); var adapter = new ParameterModelBaseConventionAdapter(convention); conventions.Add(adapter); @@ -92,10 +71,7 @@ public static PageConventionCollection Add(this PageConventionCollection convent /// The . public static PageConventionCollection AllowAnonymousToPage(this PageConventionCollection conventions, string pageName) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(pageName)) { @@ -134,10 +110,7 @@ public static PageConventionCollection AllowAnonymousToAreaPage( string areaName, string pageName) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(areaName)) { @@ -171,10 +144,7 @@ public static PageConventionCollection AllowAnonymousToAreaPage( /// The . public static PageConventionCollection AllowAnonymousToFolder(this PageConventionCollection conventions, string folderPath) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(folderPath)) { @@ -213,10 +183,7 @@ public static PageConventionCollection AllowAnonymousToAreaFolder( string areaName, string folderPath) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(areaName)) { @@ -251,10 +218,7 @@ public static PageConventionCollection AllowAnonymousToAreaFolder( /// The . public static PageConventionCollection AuthorizePage(this PageConventionCollection conventions, string pageName, string policy) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(pageName)) { @@ -320,10 +284,7 @@ public static PageConventionCollection AuthorizeAreaPage( string pageName, string policy) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(areaName)) { @@ -358,10 +319,7 @@ public static PageConventionCollection AuthorizeAreaPage( /// The . public static PageConventionCollection AuthorizeFolder(this PageConventionCollection conventions, string folderPath, string policy) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(folderPath)) { @@ -427,10 +385,7 @@ public static PageConventionCollection AuthorizeAreaFolder( string folderPath, string policy) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(areaName)) { @@ -469,20 +424,14 @@ public static PageConventionCollection AuthorizeAreaFolder( /// The . public static PageConventionCollection AddPageRoute(this PageConventionCollection conventions, string pageName, [StringSyntax("Route")] string route) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(pageName)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(pageName)); } - if (route == null) - { - throw new ArgumentNullException(nameof(route)); - } + ArgumentNullException.ThrowIfNull(route); conventions.AddPageRouteModelConvention(pageName, AddPageRouteThunk(route)); @@ -514,10 +463,7 @@ public static PageConventionCollection AddAreaPageRoute( string pageName, [StringSyntax("Route")] string route) { - if (conventions == null) - { - throw new ArgumentNullException(nameof(conventions)); - } + ArgumentNullException.ThrowIfNull(conventions); if (string.IsNullOrEmpty(areaName)) { @@ -529,10 +475,7 @@ public static PageConventionCollection AddAreaPageRoute( throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(pageName)); } - if (route == null) - { - throw new ArgumentNullException(nameof(route)); - } + ArgumentNullException.ThrowIfNull(route); conventions.AddAreaPageRouteModelConvention(areaName, pageName, AddPageRouteThunk(route)); diff --git a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesOptionsSetup.cs b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesOptionsSetup.cs index 481cb2a0a55d..408629e47bb7 100644 --- a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesOptionsSetup.cs +++ b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesOptionsSetup.cs @@ -18,10 +18,7 @@ public RazorPagesOptionsSetup(IServiceProvider serviceProvider) public void Configure(RazorPagesOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options.Conventions = new PageConventionCollection(_serviceProvider); } diff --git a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesRazorViewEngineOptionsSetup.cs b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesRazorViewEngineOptionsSetup.cs index a72243f8144d..8aebe16588de 100644 --- a/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesRazorViewEngineOptionsSetup.cs +++ b/src/Mvc/Mvc.RazorPages/src/DependencyInjection/RazorPagesRazorViewEngineOptionsSetup.cs @@ -20,10 +20,7 @@ public RazorPagesRazorViewEngineOptionsSetup(IOptions pagesOp public void Configure(RazorViewEngineOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); var rootDirectory = _pagesOptions.RootDirectory; Debug.Assert(!string.IsNullOrEmpty(rootDirectory)); diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutedContext.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutedContext.cs index 6190d0073f0d..3491a2913c78 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutedContext.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutedContext.cs @@ -31,10 +31,7 @@ public PageHandlerExecutedContext( object handlerInstance) : base(pageContext, filters) { - if (handlerInstance == null) - { - throw new ArgumentNullException(nameof(handlerInstance)); - } + ArgumentNullException.ThrowIfNull(handlerInstance); HandlerMethod = handlerMethod; HandlerInstance = handlerInstance; diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutingContext.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutingContext.cs index d67659a301fc..5a53ee1a290e 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutingContext.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerExecutingContext.cs @@ -29,15 +29,8 @@ public PageHandlerExecutingContext( object handlerInstance) : base(pageContext, filters) { - if (handlerArguments == null) - { - throw new ArgumentNullException(nameof(handlerArguments)); - } - - if (handlerInstance == null) - { - throw new ArgumentNullException(nameof(handlerInstance)); - } + ArgumentNullException.ThrowIfNull(handlerArguments); + ArgumentNullException.ThrowIfNull(handlerInstance); HandlerMethod = handlerMethod; HandlerArguments = handlerArguments; diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerPageFilter.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerPageFilter.cs index c968d329873d..a0d35e64d458 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerPageFilter.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerPageFilter.cs @@ -14,15 +14,8 @@ internal sealed class PageHandlerPageFilter : IAsyncPageFilter, IOrderedFilter public Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); var handlerInstance = context.HandlerInstance; if (handlerInstance == null) @@ -48,10 +41,7 @@ public Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, Pag public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.HandlerInstance is IAsyncPageFilter asyncPageFilter) { diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerResultFIlter.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerResultFIlter.cs index 79c4752b6d14..165ffb62988d 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerResultFIlter.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerResultFIlter.cs @@ -14,15 +14,8 @@ internal sealed class PageHandlerResultFilter : IAsyncResultFilter, IOrderedFilt public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); var handler = context.Controller; if (handler == null) diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerSelectedContext.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerSelectedContext.cs index 8127d2f98825..8f1b7225f8cb 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerSelectedContext.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageHandlerSelectedContext.cs @@ -25,10 +25,7 @@ public PageHandlerSelectedContext( object handlerInstance) : base(pageContext, filters) { - if (handlerInstance == null) - { - throw new ArgumentNullException(nameof(handlerInstance)); - } + ArgumentNullException.ThrowIfNull(handlerInstance); HandlerInstance = handlerInstance; } diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageResponseCacheFilter.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageResponseCacheFilter.cs index 47c8991c395e..ee927dc72e82 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageResponseCacheFilter.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageResponseCacheFilter.cs @@ -85,10 +85,7 @@ public void OnPageHandlerSelected(PageHandlerSelectedContext context) public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.IsEffectivePolicy(this)) { diff --git a/src/Mvc/Mvc.RazorPages/src/Filters/PageSaveTempDataPropertyFilterFactory.cs b/src/Mvc/Mvc.RazorPages/src/Filters/PageSaveTempDataPropertyFilterFactory.cs index da1157fc9aaf..abc15d5d76cc 100644 --- a/src/Mvc/Mvc.RazorPages/src/Filters/PageSaveTempDataPropertyFilterFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/Filters/PageSaveTempDataPropertyFilterFactory.cs @@ -19,10 +19,7 @@ public PageSaveTempDataPropertyFilterFactory(IReadOnlyList pr public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ArgumentNullException.ThrowIfNull(serviceProvider); var service = serviceProvider.GetRequiredService(); service.Properties = Properties; diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageActivatorProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageActivatorProvider.cs index a4f2f88f9d85..21c2a13b8c26 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageActivatorProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageActivatorProvider.cs @@ -19,10 +19,7 @@ internal sealed class DefaultPageActivatorProvider : IPageActivatorProvider /// public Func CreateActivator(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); var pageTypeInfo = actionDescriptor.PageTypeInfo?.AsType(); if (pageTypeInfo == null) @@ -38,10 +35,7 @@ public Func CreateActivator(CompiledPageAction public Action? CreateReleaser(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (typeof(IDisposable).GetTypeInfo().IsAssignableFrom(actionDescriptor.PageTypeInfo)) { @@ -53,10 +47,7 @@ public Func CreateActivator(CompiledPageAction public Func? CreateAsyncReleaser(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (typeof(IAsyncDisposable).GetTypeInfo().IsAssignableFrom(actionDescriptor.PageTypeInfo)) { @@ -88,20 +79,9 @@ private static Func CreatePageFactory(Type pag private static void Dispose(PageContext context, ViewContext viewContext, object page) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(page); ((IDisposable)page).Dispose(); } @@ -114,20 +94,9 @@ private static ValueTask SyncAsyncDispose(PageContext context, ViewContext viewC private static ValueTask AsyncDispose(PageContext context, ViewContext viewContext, object page) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(page); return ((IAsyncDisposable)page).DisposeAsync(); } diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs index 2a6a2dc3231c..74c64c45355d 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageFactoryProvider.cs @@ -69,20 +69,14 @@ public Func CreatePageFactory(CompiledPageActi public Action? CreatePageDisposer(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); return _pageActivator.CreateReleaser(descriptor); } public Func? CreateAsyncPageDisposer(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); return _pageActivator.CreateAsyncReleaser(descriptor); } diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageLoader.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageLoader.cs index 0ddaf3042a84..f56870c429f8 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageLoader.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageLoader.cs @@ -37,10 +37,7 @@ public override Task LoadAsync(PageActionDescripto public override Task LoadAsync(PageActionDescriptor actionDescriptor, EndpointMetadataCollection endpointMetadata) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (actionDescriptor is CompiledPageActionDescriptor compiledPageActionDescriptor) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelActivatorProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelActivatorProvider.cs index ebf471a2bcdc..23675a4bfc39 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelActivatorProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelActivatorProvider.cs @@ -18,10 +18,7 @@ internal sealed class DefaultPageModelActivatorProvider : IPageModelActivatorPro /// public Func CreateActivator(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); var modelTypeInfo = actionDescriptor.ModelTypeInfo?.AsType(); if (modelTypeInfo == null) @@ -38,10 +35,7 @@ public Func CreateActivator(CompiledPageActionDescriptor ac public Action? CreateReleaser(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (typeof(IDisposable).GetTypeInfo().IsAssignableFrom(actionDescriptor.ModelTypeInfo)) { @@ -53,10 +47,7 @@ public Func CreateActivator(CompiledPageActionDescriptor ac public Func? CreateAsyncReleaser(CompiledPageActionDescriptor actionDescriptor) { - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(actionDescriptor); if (typeof(IAsyncDisposable).GetTypeInfo().IsAssignableFrom(actionDescriptor.ModelTypeInfo)) { @@ -73,30 +64,16 @@ public Func CreateActivator(CompiledPageActionDescriptor ac private static void Dispose(PageContext context, object page) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(page); ((IDisposable)page).Dispose(); } private static ValueTask DisposeAsync(PageContext context, object page) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (page == null) - { - throw new ArgumentNullException(nameof(page)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(page); return ((IAsyncDisposable)page).DisposeAsync(); } diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelFactoryProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelFactoryProvider.cs index 928a5a77c318..fa0d6960d7f3 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelFactoryProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DefaultPageModelFactoryProvider.cs @@ -19,10 +19,7 @@ public DefaultPageModelFactoryProvider(IPageModelActivatorProvider modelActivato public Func? CreateModelFactory(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); if (descriptor.ModelTypeInfo == null) { @@ -50,10 +47,7 @@ public DefaultPageModelFactoryProvider(IPageModelActivatorProvider modelActivato public Action? CreateModelDisposer(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); if (descriptor.ModelTypeInfo == null) { @@ -65,10 +59,7 @@ public DefaultPageModelFactoryProvider(IPageModelActivatorProvider modelActivato public Func? CreateAsyncModelDisposer(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); if (descriptor.ModelTypeInfo == null) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointMatcherPolicy.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointMatcherPolicy.cs index fc826bb73742..0c5453711230 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointMatcherPolicy.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointMatcherPolicy.cs @@ -19,20 +19,9 @@ internal sealed class DynamicPageEndpointMatcherPolicy : MatcherPolicy, IEndpoin public DynamicPageEndpointMatcherPolicy(DynamicPageEndpointSelectorCache selectorCache, PageLoader loader, EndpointMetadataComparer comparer) { - if (selectorCache == null) - { - throw new ArgumentNullException(nameof(selectorCache)); - } - - if (loader == null) - { - throw new ArgumentNullException(nameof(loader)); - } - - if (comparer == null) - { - throw new ArgumentNullException(nameof(comparer)); - } + ArgumentNullException.ThrowIfNull(selectorCache); + ArgumentNullException.ThrowIfNull(loader); + ArgumentNullException.ThrowIfNull(comparer); _selectorCache = selectorCache; _loader = loader; @@ -43,10 +32,7 @@ public DynamicPageEndpointMatcherPolicy(DynamicPageEndpointSelectorCache selecto public bool AppliesToEndpoints(IReadOnlyList endpoints) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); if (!ContainsDynamicEndpoints(endpoints)) { @@ -74,15 +60,8 @@ public bool AppliesToEndpoints(IReadOnlyList endpoints) public async Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } - - if (candidates == null) - { - throw new ArgumentNullException(nameof(candidates)); - } + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(candidates); DynamicPageEndpointSelector? selector = null; diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelector.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelector.cs index fd90a5b562f0..3eedf14cf1c6 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelector.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageEndpointSelector.cs @@ -14,10 +14,7 @@ internal sealed class DynamicPageEndpointSelector : IDisposable public DynamicPageEndpointSelector(EndpointDataSource dataSource) { - if (dataSource == null) - { - throw new ArgumentNullException(nameof(dataSource)); - } + ArgumentNullException.ThrowIfNull(dataSource); _dataSource = dataSource; _cache = new DataSourceDependentCache>(dataSource, Initialize); @@ -27,10 +24,7 @@ public DynamicPageEndpointSelector(EndpointDataSource dataSource) public IReadOnlyList SelectEndpoints(RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); var table = Table; var matches = table.Select(values); diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageMetadata.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageMetadata.cs index f579fffb3109..f4b726eb92aa 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageMetadata.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageMetadata.cs @@ -9,10 +9,7 @@ internal sealed class DynamicPageMetadata : IDynamicEndpointMetadata { public DynamicPageMetadata(RouteValueDictionary values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); Values = values; } diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageRouteValueTransformerMetadata.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageRouteValueTransformerMetadata.cs index fa4fe3256509..c86f4a2dd5c3 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageRouteValueTransformerMetadata.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/DynamicPageRouteValueTransformerMetadata.cs @@ -10,10 +10,7 @@ internal sealed class DynamicPageRouteValueTransformerMetadata : IDynamicEndpoin { public DynamicPageRouteValueTransformerMetadata(Type selectorType, object? state) { - if (selectorType == null) - { - throw new ArgumentNullException(nameof(selectorType)); - } + ArgumentNullException.ThrowIfNull(selectorType); if (!typeof(DynamicRouteValueTransformer).IsAssignableFrom(selectorType)) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/ExecutorFactory.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/ExecutorFactory.cs index a40adba372e0..431083f94cf3 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/ExecutorFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/ExecutorFactory.cs @@ -12,10 +12,7 @@ internal static class ExecutorFactory { public static PageHandlerExecutorDelegate CreateExecutor(HandlerMethodDescriptor handlerDescriptor) { - if (handlerDescriptor == null) - { - throw new ArgumentNullException(nameof(handlerDescriptor)); - } + ArgumentNullException.ThrowIfNull(handlerDescriptor); var handler = CreateHandlerMethod(handlerDescriptor); diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/HandleOptionsRequestsPageFilter.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/HandleOptionsRequestsPageFilter.cs index 481d599a981f..d00a338892d1 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/HandleOptionsRequestsPageFilter.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/HandleOptionsRequestsPageFilter.cs @@ -34,10 +34,7 @@ public void OnPageHandlerExecuted(PageHandlerExecutedContext context) public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.HandlerMethod == null && context.Result == null && diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvokerProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvokerProvider.cs index 2e899465b441..19f9ff1c7da8 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvokerProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageActionInvokerProvider.cs @@ -60,10 +60,7 @@ public PageActionInvokerProvider( public void OnProvidersExecuting(ActionInvokerProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var actionContext = context.ActionContext; diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageBinderFactory.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageBinderFactory.cs index a11b1fd1b223..b628367d5a9b 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageBinderFactory.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageBinderFactory.cs @@ -16,15 +16,8 @@ public static Func CreatePropertyBinder( IModelBinderFactory modelBinderFactory, CompiledPageActionDescriptor actionDescriptor) { - if (parameterBinder == null) - { - throw new ArgumentNullException(nameof(parameterBinder)); - } - - if (actionDescriptor == null) - { - throw new ArgumentNullException(nameof(actionDescriptor)); - } + ArgumentNullException.ThrowIfNull(parameterBinder); + ArgumentNullException.ThrowIfNull(actionDescriptor); var properties = actionDescriptor.BoundProperties; if (properties == null || properties.Count == 0) diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs index 36cabd9e824f..f9f505f96742 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/PageResultExecutor.cs @@ -50,15 +50,8 @@ public PageResultExecutor( /// public virtual Task ExecuteAsync(PageContext pageContext, PageResult result) { - if (pageContext == null) - { - throw new ArgumentNullException(nameof(pageContext)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(pageContext); + ArgumentNullException.ThrowIfNull(result); if (result.Model != null) { diff --git a/src/Mvc/Mvc.RazorPages/src/Infrastructure/ServiceBasedPageModelActivatorProvider.cs b/src/Mvc/Mvc.RazorPages/src/Infrastructure/ServiceBasedPageModelActivatorProvider.cs index c493755a525d..2b980bdd19c5 100644 --- a/src/Mvc/Mvc.RazorPages/src/Infrastructure/ServiceBasedPageModelActivatorProvider.cs +++ b/src/Mvc/Mvc.RazorPages/src/Infrastructure/ServiceBasedPageModelActivatorProvider.cs @@ -13,10 +13,7 @@ public class ServiceBasedPageModelActivatorProvider : IPageModelActivatorProvide /// public Func CreateActivator(CompiledPageActionDescriptor descriptor) { - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } + ArgumentNullException.ThrowIfNull(descriptor); var modelType = descriptor.ModelTypeInfo?.AsType(); if (modelType == null) diff --git a/src/Mvc/Mvc.RazorPages/src/PageActionDescriptor.cs b/src/Mvc/Mvc.RazorPages/src/PageActionDescriptor.cs index dd71d40c36f3..ab989b2ef33b 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageActionDescriptor.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageActionDescriptor.cs @@ -25,10 +25,7 @@ public PageActionDescriptor() /// The to copy from. public PageActionDescriptor(PageActionDescriptor other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); RelativePath = other.RelativePath; ViewEnginePath = other.ViewEnginePath; @@ -79,10 +76,7 @@ public override string? DisplayName set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); base.DisplayName = value; } diff --git a/src/Mvc/Mvc.RazorPages/src/PageBase.cs b/src/Mvc/Mvc.RazorPages/src/PageBase.cs index 84a3d3c3e3f0..fc54e578cb7d 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageBase.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageBase.cs @@ -140,10 +140,7 @@ public virtual BadRequestObjectResult BadRequest(object error) /// The created for the response. public virtual BadRequestObjectResult BadRequest(ModelStateDictionary modelState) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); return new BadRequestObjectResult(modelState); } @@ -1302,10 +1299,7 @@ public virtual Task TryUpdateModelAsync( TModel model) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryUpdateModelAsync(model, prefix: string.Empty); } @@ -1324,15 +1318,8 @@ public virtual async Task TryUpdateModelAsync( string prefix) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(prefix); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -1359,20 +1346,9 @@ public virtual Task TryUpdateModelAsync( IValueProvider valueProvider) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(valueProvider); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -1401,15 +1377,8 @@ public async Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(includeExpressions); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -1444,15 +1413,8 @@ public async Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(propertyFilter); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -1490,20 +1452,9 @@ public Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(includeExpressions); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -1534,20 +1485,9 @@ public Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -1574,15 +1514,8 @@ public virtual async Task TryUpdateModelAsync( Type modelType, string prefix) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -1619,25 +1552,10 @@ public Task TryUpdateModelAsync( IValueProvider valueProvider, Func propertyFilter) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -1659,10 +1577,7 @@ public Task TryUpdateModelAsync( public virtual bool TryValidateModel( object model) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryValidateModel(model, prefix: null); } @@ -1678,10 +1593,7 @@ public virtual bool TryValidateModel( object model, string? prefix) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); ObjectValidator.Validate( PageContext, diff --git a/src/Mvc/Mvc.RazorPages/src/PageContext.cs b/src/Mvc/Mvc.RazorPages/src/PageContext.cs index cda5c706ca3c..20ec6222a2eb 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageContext.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageContext.cs @@ -61,10 +61,7 @@ internal PageContext( get => _actionDescriptor!; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _actionDescriptor = value; base.ActionDescriptor = value; @@ -87,10 +84,7 @@ public virtual IList ValueProviderFactories } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _valueProviderFactories = value; } @@ -104,10 +98,7 @@ public virtual ViewDataDictionary ViewData get => _viewData!; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _viewData = value; } @@ -121,10 +112,7 @@ public virtual IList> ViewStartFactories get => _viewStartFactories!; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _viewStartFactories = value; } diff --git a/src/Mvc/Mvc.RazorPages/src/PageModel.cs b/src/Mvc/Mvc.RazorPages/src/PageModel.cs index 8aea3c32230c..45138f35896e 100644 --- a/src/Mvc/Mvc.RazorPages/src/PageModel.cs +++ b/src/Mvc/Mvc.RazorPages/src/PageModel.cs @@ -49,10 +49,7 @@ public PageContext PageContext } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _pageContext = value; } @@ -105,10 +102,7 @@ public ITempDataDictionary TempData } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _tempData = value; } @@ -131,10 +125,7 @@ public IUrlHelper Url } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _urlHelper = value; } @@ -194,10 +185,7 @@ private IModelBinderFactory ModelBinderFactory protected internal Task TryUpdateModelAsync(TModel model) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryUpdateModelAsync(model, name: string.Empty); } @@ -213,15 +201,8 @@ protected internal Task TryUpdateModelAsync(TModel model) protected internal async Task TryUpdateModelAsync(TModel model, string name) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(name); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -248,20 +229,9 @@ protected internal Task TryUpdateModelAsync( IValueProvider valueProvider) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(valueProvider); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -290,15 +260,8 @@ protected internal async Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(includeExpressions); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -333,15 +296,8 @@ protected internal async Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(propertyFilter); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -379,20 +335,9 @@ protected internal Task TryUpdateModelAsync( params Expression>[] includeExpressions) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (includeExpressions == null) - { - throw new ArgumentNullException(nameof(includeExpressions)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(includeExpressions); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -423,20 +368,9 @@ protected internal Task TryUpdateModelAsync( Func propertyFilter) where TModel : class { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -463,15 +397,8 @@ protected internal async Task TryUpdateModelAsync( Type modelType, string name) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); var (success, valueProvider) = await CompositeValueProvider.TryCreateAsync(PageContext, PageContext.ValueProviderFactories); if (!success) @@ -508,25 +435,10 @@ protected internal Task TryUpdateModelAsync( IValueProvider valueProvider, Func propertyFilter) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } - - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } - - if (propertyFilter == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(valueProvider); + ArgumentNullException.ThrowIfNull(propertyFilter); return ModelBindingHelper.TryUpdateModelAsync( model, @@ -562,10 +474,7 @@ public virtual BadRequestObjectResult BadRequest(object error) /// The created for the response. public virtual BadRequestObjectResult BadRequest(ModelStateDictionary modelState) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } + ArgumentNullException.ThrowIfNull(modelState); return new BadRequestObjectResult(modelState); } @@ -1747,10 +1656,7 @@ public virtual ViewComponentResult ViewComponent(Type componentType, object? arg public virtual bool TryValidateModel( object model) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); return TryValidateModel(model, name: null); } @@ -1766,10 +1672,7 @@ public virtual bool TryValidateModel( object model, string? name) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } + ArgumentNullException.ThrowIfNull(model); ObjectValidator.Validate( PageContext, @@ -1811,10 +1714,7 @@ public virtual void OnPageHandlerExecuted(PageHandlerExecutedContext context) /// A that on completion indicates the filter has executed. public virtual Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); OnPageHandlerSelected(context); return Task.CompletedTask; @@ -1830,15 +1730,8 @@ public virtual Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext conte /// A that on completion indicates the filter has executed. public virtual async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); OnPageHandlerExecuting(context); if (context.Result == null) diff --git a/src/Mvc/Mvc.TagHelpers/src/AnchorTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/AnchorTagHelper.cs index 5035a0c9f208..98bf236213fd 100644 --- a/src/Mvc/Mvc.TagHelpers/src/AnchorTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/AnchorTagHelper.cs @@ -162,15 +162,8 @@ public IDictionary RouteValues /// Does nothing if user provides an href attribute. public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // If "href" is already set, it means the user is attempting to use a normal anchor. if (output.Attributes.ContainsName(Href)) diff --git a/src/Mvc/Mvc.TagHelpers/src/AttributeMatcher.cs b/src/Mvc/Mvc.TagHelpers/src/AttributeMatcher.cs index 13169724a615..497ba51b5ea9 100644 --- a/src/Mvc/Mvc.TagHelpers/src/AttributeMatcher.cs +++ b/src/Mvc/Mvc.TagHelpers/src/AttributeMatcher.cs @@ -26,20 +26,9 @@ public static bool TryDetermineMode( Func compare, out TMode result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (modeInfos == null) - { - throw new ArgumentNullException(nameof(modeInfos)); - } - - if (compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(modeInfos); + ArgumentNullException.ThrowIfNull(compare); var foundResult = false; result = default; diff --git a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperFormatter.cs b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperFormatter.cs index 87aa688071c6..ea31ba1a1593 100644 --- a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperFormatter.cs +++ b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperFormatter.cs @@ -15,10 +15,7 @@ public class DistributedCacheTagHelperFormatter : IDistributedCacheTagHelperForm /// public Task SerializeAsync(DistributedCacheTagHelperFormattingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Html == null) { @@ -35,10 +32,7 @@ public Task SerializeAsync(DistributedCacheTagHelperFormattingContext co /// public Task DeserializeAsync(byte[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); var content = Encoding.UTF8.GetString(value); return Task.FromResult(new HtmlString(content)); diff --git a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs index d296cdb2c8b8..a188825c8067 100644 --- a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs +++ b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs @@ -49,25 +49,10 @@ public DistributedCacheTagHelperService( HtmlEncoder HtmlEncoder, ILoggerFactory loggerFactory) { - if (storage == null) - { - throw new ArgumentNullException(nameof(storage)); - } - - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } - - if (HtmlEncoder == null) - { - throw new ArgumentNullException(nameof(HtmlEncoder)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(formatter); + ArgumentNullException.ThrowIfNull(HtmlEncoder); + ArgumentNullException.ThrowIfNull(loggerFactory); _formatter = formatter; _storage = storage; diff --git a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperStorage.cs b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperStorage.cs index 8f45c260132d..afa24771c669 100644 --- a/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperStorage.cs +++ b/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperStorage.cs @@ -25,10 +25,7 @@ public DistributedCacheTagHelperStorage(IDistributedCache distributedCache) /// public Task GetAsync(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _distributedCache.GetAsync(key); } @@ -36,15 +33,8 @@ public Task GetAsync(string key) /// public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); return _distributedCache.SetAsync(key, value, options); } diff --git a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs index 066cbdb07869..6583986e405d 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs @@ -82,15 +82,8 @@ public RenderMode RenderMode /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); if (_renderMode is null) { diff --git a/src/Mvc/Mvc.TagHelpers/src/DependencyInjection/TagHelperExtensions.cs b/src/Mvc/Mvc.TagHelpers/src/DependencyInjection/TagHelperExtensions.cs index 605038dc42bb..d19ca4dde7cc 100644 --- a/src/Mvc/Mvc.TagHelpers/src/DependencyInjection/TagHelperExtensions.cs +++ b/src/Mvc/Mvc.TagHelpers/src/DependencyInjection/TagHelperExtensions.cs @@ -19,10 +19,7 @@ public static class TagHelperServicesExtensions /// The . public static IMvcCoreBuilder AddCacheTagHelper(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); AddCacheTagHelperServices(builder.Services); @@ -37,15 +34,8 @@ public static IMvcCoreBuilder AddCacheTagHelper(this IMvcCoreBuilder builder) /// The . public static IMvcBuilder AddCacheTagHelperLimits(this IMvcBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure(configure); @@ -60,15 +50,8 @@ public static IMvcBuilder AddCacheTagHelperLimits(this IMvcBuilder builder, Acti /// The . public static IMvcCoreBuilder AddCacheTagHelperLimits(this IMvcCoreBuilder builder, Action configure) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configure); builder.Services.Configure(configure); diff --git a/src/Mvc/Mvc.TagHelpers/src/DistributedCacheTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/DistributedCacheTagHelper.cs index 1b5e83f626cb..4d6bc16d24fa 100644 --- a/src/Mvc/Mvc.TagHelpers/src/DistributedCacheTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/DistributedCacheTagHelper.cs @@ -52,15 +52,8 @@ public DistributedCacheTagHelper( /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); IHtmlContent content; if (Enabled) diff --git a/src/Mvc/Mvc.TagHelpers/src/EnvironmentTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/EnvironmentTagHelper.cs index 8f58eacf8f23..515dc88359d8 100644 --- a/src/Mvc/Mvc.TagHelpers/src/EnvironmentTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/EnvironmentTagHelper.cs @@ -66,15 +66,8 @@ public EnvironmentTagHelper(IWebHostEnvironment hostingEnvironment) /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Always strip the outer tag name as we never want to render output.TagName = null; diff --git a/src/Mvc/Mvc.TagHelpers/src/FormActionTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/FormActionTagHelper.cs index a6ebe87517b4..eca6ab29a0e3 100644 --- a/src/Mvc/Mvc.TagHelpers/src/FormActionTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/FormActionTagHelper.cs @@ -177,15 +177,8 @@ public IDictionary RouteValues /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // If "FormAction" is already set, it means the user is attempting to use a normal button or input element. if (output.Attributes.ContainsName(FormAction)) diff --git a/src/Mvc/Mvc.TagHelpers/src/FormTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/FormTagHelper.cs index 813c419612e6..b95c8a626b2e 100644 --- a/src/Mvc/Mvc.TagHelpers/src/FormTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/FormTagHelper.cs @@ -147,15 +147,8 @@ public IDictionary RouteValues /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); if (Method != null) { diff --git a/src/Mvc/Mvc.TagHelpers/src/ImageTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ImageTagHelper.cs index a05e4ec10430..9cdd30d32e13 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ImageTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ImageTagHelper.cs @@ -109,15 +109,8 @@ public ImageTagHelper( /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); output.CopyHtmlAttribute(SrcAttributeName, context); ProcessUrlAttribute(SrcAttributeName, output); diff --git a/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs index 2c975e7b9410..ae7f8f66fbe8 100644 --- a/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/InputTagHelper.cs @@ -141,15 +141,8 @@ public InputTagHelper(IHtmlGenerator generator) /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attributes that are also well-known HTML attributes. Must be done prior to any copying // from a TagBuilder. diff --git a/src/Mvc/Mvc.TagHelpers/src/LabelTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/LabelTagHelper.cs index 6aefa16b9e83..e6a890f1f3ca 100644 --- a/src/Mvc/Mvc.TagHelpers/src/LabelTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/LabelTagHelper.cs @@ -49,15 +49,8 @@ public LabelTagHelper(IHtmlGenerator generator) /// Does nothing if is null. public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); var tagBuilder = Generator.GenerateLabel( ViewContext, diff --git a/src/Mvc/Mvc.TagHelpers/src/LinkTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/LinkTagHelper.cs index ceb8cb8d80a0..f7950deae6d6 100644 --- a/src/Mvc/Mvc.TagHelpers/src/LinkTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/LinkTagHelper.cs @@ -247,15 +247,8 @@ private StringWriter StringWriter /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attribute that is also a well-known HTML attribute. if (Href != null) diff --git a/src/Mvc/Mvc.TagHelpers/src/OptionTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/OptionTagHelper.cs index 3ad9ae7fb2e1..39e3596df1a0 100644 --- a/src/Mvc/Mvc.TagHelpers/src/OptionTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/OptionTagHelper.cs @@ -58,15 +58,8 @@ public OptionTagHelper(IHtmlGenerator generator) /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attributes that are also well-known HTML attributes. if (Value != null) diff --git a/src/Mvc/Mvc.TagHelpers/src/PartialTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/PartialTagHelper.cs index ab0036dcd512..890a92d6c2ec 100644 --- a/src/Mvc/Mvc.TagHelpers/src/PartialTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/PartialTagHelper.cs @@ -103,15 +103,8 @@ public object Model /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Reset the TagName. We don't want `partial` to render. output.TagName = null; diff --git a/src/Mvc/Mvc.TagHelpers/src/PersistComponentStateTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/PersistComponentStateTagHelper.cs index c8ef81be8347..bd48227d2179 100644 --- a/src/Mvc/Mvc.TagHelpers/src/PersistComponentStateTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/PersistComponentStateTagHelper.cs @@ -44,15 +44,8 @@ public PersistenceMode? PersistenceMode /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); var services = ViewContext.HttpContext.RequestServices; var manager = services.GetRequiredService(); diff --git a/src/Mvc/Mvc.TagHelpers/src/RenderAtEndOfFormTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/RenderAtEndOfFormTagHelper.cs index c4d0ed7f1dfe..a10e96e0bb42 100644 --- a/src/Mvc/Mvc.TagHelpers/src/RenderAtEndOfFormTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/RenderAtEndOfFormTagHelper.cs @@ -31,10 +31,7 @@ public class RenderAtEndOfFormTagHelper : TagHelper /// public override void Init(TagHelperContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Push the new FormContext. ViewContext.FormContext = new FormContext @@ -46,15 +43,8 @@ public override void Init(TagHelperContext context) /// public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); await output.GetChildContentAsync(); diff --git a/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs index b47831fdd5ed..3fdaa8410a31 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ScriptTagHelper.cs @@ -214,15 +214,8 @@ private StringWriter StringWriter /// public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attribute that is also a well-known HTML attribute. if (Src != null) diff --git a/src/Mvc/Mvc.TagHelpers/src/SelectTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/SelectTagHelper.cs index 67202a09cba4..7390fd86eb27 100644 --- a/src/Mvc/Mvc.TagHelpers/src/SelectTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/SelectTagHelper.cs @@ -72,10 +72,7 @@ public SelectTagHelper(IHtmlGenerator generator) /// public override void Init(TagHelperContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (For == null) { @@ -113,15 +110,8 @@ public override void Init(TagHelperContext context) /// Does nothing if is null. public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attribute that is also a well-known HTML attribute. Must be done prior to any copying // from a TagBuilder. diff --git a/src/Mvc/Mvc.TagHelpers/src/TextAreaTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/TextAreaTagHelper.cs index 783bdcacf3ca..bbcade7a614d 100644 --- a/src/Mvc/Mvc.TagHelpers/src/TextAreaTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/TextAreaTagHelper.cs @@ -58,15 +58,8 @@ public TextAreaTagHelper(IHtmlGenerator generator) /// Does nothing if is null. public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); // Pass through attribute that is also a well-known HTML attribute. Must be done prior to any copying // from a TagBuilder. diff --git a/src/Mvc/Mvc.TagHelpers/src/ValidationMessageTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ValidationMessageTagHelper.cs index 13b1567cb939..625f09ec509f 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ValidationMessageTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ValidationMessageTagHelper.cs @@ -51,15 +51,8 @@ public ValidationMessageTagHelper(IHtmlGenerator generator) /// Does nothing if is null. public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); if (For != null) { diff --git a/src/Mvc/Mvc.TagHelpers/src/ValidationSummaryTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ValidationSummaryTagHelper.cs index 7258872efb64..4e60104a6cc9 100644 --- a/src/Mvc/Mvc.TagHelpers/src/ValidationSummaryTagHelper.cs +++ b/src/Mvc/Mvc.TagHelpers/src/ValidationSummaryTagHelper.cs @@ -79,15 +79,8 @@ public ValidationSummary ValidationSummary /// Does nothing if is . public override void Process(TagHelperContext context, TagHelperOutput output) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(output); if (ValidationSummary == ValidationSummary.None) { diff --git a/src/Mvc/Mvc.Testing/src/Handlers/RedirectHandler.cs b/src/Mvc/Mvc.Testing/src/Handlers/RedirectHandler.cs index 06f72a0cef3d..9621dcce4a7a 100644 --- a/src/Mvc/Mvc.Testing/src/Handlers/RedirectHandler.cs +++ b/src/Mvc/Mvc.Testing/src/Handlers/RedirectHandler.cs @@ -31,10 +31,7 @@ public RedirectHandler() /// equal or greater than 0. public RedirectHandler(int maxRedirects) { - if (maxRedirects <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxRedirects)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxRedirects); MaxRedirects = maxRedirects; } diff --git a/src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs b/src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs index 4d458ed837e8..39004a181e76 100644 --- a/src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs +++ b/src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs @@ -505,10 +505,7 @@ public HttpClient CreateDefaultClient(params DelegatingHandler[] handlers) /// The instance getting configured. protected virtual void ConfigureClient(HttpClient client) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); client.BaseAddress = new Uri("http://localhost"); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/AntiforgeryExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/AntiforgeryExtensions.cs index cda0eb567e12..8302be1274a0 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/AntiforgeryExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/AntiforgeryExtensions.cs @@ -30,15 +30,8 @@ public static class AntiforgeryExtensions /// public static IHtmlContent GetHtml(this IAntiforgery antiforgery, HttpContext httpContext) { - if (antiforgery == null) - { - throw new ArgumentNullException(nameof(antiforgery)); - } - - if (httpContext == null) - { - throw new ArgumentNullException(nameof(httpContext)); - } + ArgumentNullException.ThrowIfNull(antiforgery); + ArgumentNullException.ThrowIfNull(httpContext); var tokenSet = antiforgery.GetAndStoreTokens(httpContext); return new InputContent(tokenSet); diff --git a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs index eb0eb0bdff5f..fbd2d2a43f53 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs @@ -20,10 +20,7 @@ public string? this[string key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var index = Find(key); if (index < 0) @@ -38,10 +35,7 @@ public string? this[string key] set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var item = new KeyValuePair(key, value); var index = Find(key); @@ -183,10 +177,7 @@ public void Add(KeyValuePair item) /// public void Add(string key, string? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); Add(new KeyValuePair(key, value)); } @@ -217,10 +208,7 @@ public bool Contains(KeyValuePair item) /// public bool ContainsKey(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); if (Count == 0) { @@ -233,10 +221,7 @@ public bool ContainsKey(string key) /// public void CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0 || arrayIndex >= array.Length) { @@ -286,10 +271,7 @@ public bool Remove(KeyValuePair item) /// public bool Remove(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var index = Find(key); if (index < 0) @@ -306,10 +288,7 @@ public bool Remove(string key) /// public bool TryGetValue(string key, out string? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); var index = Find(key); if (index < 0) @@ -406,10 +385,7 @@ public void Clear() public bool Contains(string item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); for (var i = 0; i < _attributes.Count; i++) { @@ -424,10 +400,7 @@ public bool Contains(string item) public void CopyTo(string[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0 || arrayIndex >= array.Length) { @@ -532,10 +505,7 @@ public bool Contains(string? item) public void CopyTo(string?[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0 || arrayIndex >= array.Length) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs index f3fce33228d8..c73e4068cd30 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/MemoryPoolViewBufferScope.cs @@ -35,15 +35,8 @@ public MemoryPoolViewBufferScope(ArrayPool viewBufferPool, Arra /// public ViewBufferValue[] GetPage(int pageSize) { - if (pageSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(pageSize)); - } - - if (_disposed) - { - throw new ObjectDisposedException(typeof(MemoryPoolViewBufferScope).FullName); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); + ObjectDisposedException.ThrowIf(_disposed, this); if (_leased == null) { @@ -77,10 +70,7 @@ public ViewBufferValue[] GetPage(int pageSize) /// public void ReturnSegment(ViewBufferValue[] segment) { - if (segment == null) - { - throw new ArgumentNullException(nameof(segment)); - } + ArgumentNullException.ThrowIfNull(segment); Array.Clear(segment, 0, segment.Length); @@ -95,10 +85,7 @@ public void ReturnSegment(ViewBufferValue[] segment) /// public TextWriter CreateWriter(TextWriter writer) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); return new PagedBufferedTextWriter(_charPool, writer); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/PagedBufferedTextWriter.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/PagedBufferedTextWriter.cs index 2d2fe5e9a50a..68fed2edf3b8 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/PagedBufferedTextWriter.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/PagedBufferedTextWriter.cs @@ -84,10 +84,7 @@ public override void Write(char[] buffer) public override void Write(char[] buffer, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); _charBuffer.Append(buffer, index, count); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs index 19df45228675..c6b9628704f5 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs @@ -33,15 +33,8 @@ internal sealed class ViewBuffer : IHtmlContentBuilder /// The size of buffer pages. public ViewBuffer(IViewBufferScope bufferScope, string name, int pageSize) { - if (bufferScope == null) - { - throw new ArgumentNullException(nameof(bufferScope)); - } - - if (pageSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(pageSize)); - } + ArgumentNullException.ThrowIfNull(bufferScope); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize); _bufferScope = bufferScope; _name = name; @@ -184,15 +177,8 @@ public IHtmlContentBuilder Clear() /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); for (var i = 0; i < Count; i++) { @@ -224,15 +210,8 @@ public void WriteTo(TextWriter writer, HtmlEncoder encoder) /// A which will complete once content has been written. public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); for (var i = 0; i < Count; i++) { @@ -267,10 +246,7 @@ public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder) public void CopyTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); for (var i = 0; i < Count; i++) { @@ -299,10 +275,7 @@ public void CopyTo(IHtmlContentBuilder destination) public void MoveTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); // Perf: We have an efficient implementation when the destination is another view buffer, // we can just insert our pages as-is. diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs index 67059c898292..8c93be2ca475 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBufferTextWriter.cs @@ -29,15 +29,8 @@ internal sealed class ViewBufferTextWriter : TextWriter /// The . public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentNullException.ThrowIfNull(encoding); Buffer = buffer; Encoding = encoding; @@ -54,25 +47,10 @@ public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding) /// public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding, HtmlEncoder htmlEncoder, TextWriter inner) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentNullException.ThrowIfNull(encoding); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(inner); Buffer = buffer; Encoding = encoding; @@ -102,25 +80,10 @@ public override void Write(char value) /// public override void Write(char[] buffer, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfGreaterThan(count, buffer.Length - index); Buffer.AppendHtml(new string(buffer, index, count)); } @@ -221,15 +184,8 @@ public override Task WriteAsync(char value) /// public override Task WriteAsync(char[] buffer, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } + ArgumentNullException.ThrowIfNull(buffer); + ArgumentOutOfRangeException.ThrowIfNegative(index); if (count < 0 || (buffer.Length - index < count)) { throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/Mvc/Mvc.ViewFeatures/src/CachedExpressionCompiler.cs b/src/Mvc/Mvc.ViewFeatures/src/CachedExpressionCompiler.cs index f878c5e48a4c..57c9fdc9989d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/CachedExpressionCompiler.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/CachedExpressionCompiler.cs @@ -22,10 +22,7 @@ internal static class CachedExpressionCompiler public static Func Process( Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); return Compiler.Compile(expression); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Controller.cs b/src/Mvc/Mvc.ViewFeatures/src/Controller.cs index 5463bb70f502..2c9ab5c98772 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Controller.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Controller.cs @@ -76,10 +76,7 @@ public ITempDataDictionary TempData } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _tempData = value; } @@ -347,15 +344,8 @@ public virtual Task OnActionExecutionAsync( ActionExecutingContext context, ActionExecutionDelegate next) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); OnActionExecuting(context); if (context.Result == null) diff --git a/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs index f924dd58e75c..10bf662be278 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/CookieTempDataProvider.cs @@ -55,10 +55,7 @@ public CookieTempDataProvider( /// The temp data. public IDictionary LoadTempData(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Request.Cookies.ContainsKey(_options.Cookie.Name)) { @@ -104,10 +101,7 @@ public IDictionary LoadTempData(HttpContext context) /// The values. public void SaveTempData(HttpContext context, IDictionary values) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var cookieOptions = _options.Cookie.Build(context); SetCookiePath(context, cookieOptions); diff --git a/src/Mvc/Mvc.ViewFeatures/src/DefaultEditorTemplates.cs b/src/Mvc/Mvc.ViewFeatures/src/DefaultEditorTemplates.cs index 7129c282a8ad..72b1f3b1fdd3 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DefaultEditorTemplates.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DefaultEditorTemplates.cs @@ -395,20 +395,14 @@ public static IHtmlContent NumberInputTemplate(IHtmlHelper htmlHelper) public static IHtmlContent FileInputTemplate(IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return GenerateTextBox(htmlHelper, inputType: "file"); } public static IHtmlContent FileCollectionInputTemplate(IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); var htmlAttributes = CreateHtmlAttributes(htmlHelper, className: "text-box single-line", inputType: "file"); @@ -506,10 +500,7 @@ public override string Encode(string value) public override void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullException.ThrowIfNull(output); if (characterCount == 0) { @@ -521,15 +512,8 @@ public override void Encode(TextWriter output, char[] value, int startIndex, int public override void Encode(TextWriter output, string value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(value); if (characterCount == 0) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs b/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs index f1ebb42a3d82..9674433ba5f1 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DefaultHtmlGenerator.cs @@ -60,35 +60,12 @@ public DefaultHtmlGenerator( HtmlEncoder htmlEncoder, ValidationHtmlAttributeProvider validationAttributeProvider) { - if (antiforgery == null) - { - throw new ArgumentNullException(nameof(antiforgery)); - } - - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (urlHelperFactory == null) - { - throw new ArgumentNullException(nameof(urlHelperFactory)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (validationAttributeProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeProvider)); - } + ArgumentNullException.ThrowIfNull(antiforgery); + ArgumentNullException.ThrowIfNull(optionsAccessor); + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(urlHelperFactory); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(validationAttributeProvider); _antiforgery = antiforgery; _metadataProvider = metadataProvider; @@ -156,15 +133,8 @@ public virtual TagBuilder GenerateActionLink( object routeValues, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(linkText); var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment); @@ -183,15 +153,8 @@ public virtual TagBuilder GeneratePageLink( object routeValues, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(linkText); var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.Page(pageName, pageHandler, routeValues, protocol, hostname, fragment); @@ -201,10 +164,7 @@ public virtual TagBuilder GeneratePageLink( /// public virtual IHtmlContent GenerateAntiforgery(ViewContext viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var formContext = viewContext.FormContext; if (formContext.CanRenderAtEndOfForm) @@ -231,10 +191,7 @@ public virtual TagBuilder GenerateCheckBox( bool? isChecked, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); if (modelExplorer != null) { @@ -278,10 +235,7 @@ public virtual TagBuilder GenerateHiddenForCheckbox( ModelExplorer modelExplorer, string expression) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttribute("type", GetInputTypeString(InputType.Hidden)); @@ -306,10 +260,7 @@ public virtual TagBuilder GenerateForm( string method, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var defaultMethod = false; if (string.IsNullOrEmpty(method)) @@ -349,10 +300,7 @@ public virtual TagBuilder GeneratePageForm( string method, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var action = urlHelper.Page(pageName, pageHandler, routeValues, protocol: null, host: null, fragment: fragment); @@ -368,10 +316,7 @@ public TagBuilder GenerateRouteForm( string method, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var action = urlHelper.RouteUrl(routeName, routeValues); @@ -388,10 +333,7 @@ public virtual TagBuilder GenerateHidden( bool useViewData, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); // Special-case opaque values and arbitrary binary data. if (value is byte[] byteArrayValue) @@ -422,15 +364,8 @@ public virtual TagBuilder GenerateLabel( string labelText, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(modelExplorer); var resolvedLabelText = labelText ?? modelExplorer.Metadata.DisplayName ?? @@ -467,10 +402,7 @@ public virtual TagBuilder GeneratePassword( object value, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); return GenerateInput( @@ -496,10 +428,7 @@ public virtual TagBuilder GenerateRadioButton( bool? isChecked, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (modelExplorer == null) @@ -509,10 +438,7 @@ public virtual TagBuilder GenerateRadioButton( (htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked"))) { // Note value may be null if isChecked is non-null. - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // isChecked not provided nor found in the given attributes; fall back to view data. var valueString = Convert.ToString(value, CultureInfo.CurrentCulture); @@ -567,15 +493,8 @@ public virtual TagBuilder GenerateRouteLink( object routeValues, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(linkText); var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.RouteUrl(routeName, routeValues, protocol, hostName, fragment); @@ -592,10 +511,7 @@ public TagBuilder GenerateSelect( bool allowMultiple, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var currentValues = GetCurrentValues(viewContext, modelExplorer, expression, allowMultiple); return GenerateSelect( @@ -620,10 +536,7 @@ public virtual TagBuilder GenerateSelect( bool allowMultiple, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); @@ -688,10 +601,7 @@ public virtual TagBuilder GenerateTextArea( int columns, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); if (rows < 0) { @@ -779,10 +689,7 @@ public virtual TagBuilder GenerateTextBox( string format, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); return GenerateInput( @@ -808,10 +715,7 @@ public virtual TagBuilder GenerateValidationMessage( string tag, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); @@ -901,10 +805,7 @@ public virtual TagBuilder GenerateValidationSummary( string headerTag, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var viewData = viewContext.ViewData; if (!viewContext.ClientValidationEnabled && viewData.ModelState.IsValid) @@ -1002,10 +903,7 @@ public virtual ICollection GetCurrentValues( string expression, bool allowMultiple) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var type = allowMultiple ? typeof(string[]) : typeof(string); @@ -1192,10 +1090,7 @@ protected virtual TagBuilder GenerateFormCore( string method, object htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes)); @@ -1244,10 +1139,7 @@ protected virtual TagBuilder GenerateInput( string format, IDictionary htmlAttributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); // Not valid to use TextBoxForModel() and so on in a top-level view; would end up with an unnamed input // elements. But we support the *ForModel() methods in any lower-level template, once HtmlFieldPrefix is @@ -1389,10 +1281,7 @@ protected virtual TagBuilder GenerateLink( string url, object htmlAttributes) { - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(linkText); var tagBuilder = new TagBuilder("a"); tagBuilder.InnerHtml.SetContent(linkText); @@ -1597,10 +1486,7 @@ private static IEnumerable GetSelectListItems( ViewContext viewContext, string expression) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); // Method is called only if user did not pass a select list in. They must provide select list items in the // ViewData dictionary and definitely not as the Model. (Even if the Model datatype were correct, a diff --git a/src/Mvc/Mvc.ViewFeatures/src/DefaultValidationHtmlAttributeProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/DefaultValidationHtmlAttributeProvider.cs index 1a3d24b2fba5..0fef9c1e1100 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DefaultValidationHtmlAttributeProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DefaultValidationHtmlAttributeProvider.cs @@ -29,20 +29,9 @@ public DefaultValidationHtmlAttributeProvider( IModelMetadataProvider metadataProvider, ClientValidatorCache clientValidatorCache) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (clientValidatorCache == null) - { - throw new ArgumentNullException(nameof(clientValidatorCache)); - } + ArgumentNullException.ThrowIfNull(optionsAccessor); + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(clientValidatorCache); _clientValidatorCache = clientValidatorCache; _metadataProvider = metadataProvider; @@ -57,20 +46,9 @@ public override void AddValidationAttributes( ModelExplorer modelExplorer, IDictionary attributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(modelExplorer); + ArgumentNullException.ThrowIfNull(attributes); var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null; if (formContext == null) diff --git a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcBuilderExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcBuilderExtensions.cs index 45d06c83fff0..a0ceab875c61 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcBuilderExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcBuilderExtensions.cs @@ -26,15 +26,8 @@ public static IMvcBuilder AddViewOptions( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; @@ -47,10 +40,7 @@ public static IMvcBuilder AddViewOptions( /// The . public static IMvcBuilder AddViewComponentsAsServices(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); var feature = new ViewComponentFeature(); builder.PartManager.PopulateFeature(feature); @@ -73,10 +63,7 @@ public static IMvcBuilder AddViewComponentsAsServices(this IMvcBuilder builder) /// The . public static IMvcBuilder AddSessionStateTempDataProvider(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); // Ensure the TempData basics are registered. MvcViewFeaturesMvcCoreBuilderExtensions.AddViewServices(builder.Services); @@ -95,10 +82,7 @@ public static IMvcBuilder AddSessionStateTempDataProvider(this IMvcBuilder build /// The . public static IMvcBuilder AddCookieTempDataProvider(this IMvcBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); // Ensure the TempData basics are registered. MvcViewFeaturesMvcCoreBuilderExtensions.AddViewServices(builder.Services); @@ -123,15 +107,8 @@ public static IMvcBuilder AddCookieTempDataProvider( this IMvcBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddCookieTempDataProvider(builder); builder.Services.Configure(setupAction); diff --git a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs index dd76e54f2449..cac20243b187 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewFeaturesMvcCoreBuilderExtensions.cs @@ -38,10 +38,7 @@ public static class MvcViewFeaturesMvcCoreBuilderExtensions /// The . public static IMvcCoreBuilder AddViews(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); builder.AddDataAnnotations(); AddViewComponentApplicationPartsProviders(builder.PartManager); @@ -57,10 +54,7 @@ public static IMvcCoreBuilder AddViews(this IMvcCoreBuilder builder) /// The . public static IMvcCoreBuilder AddCookieTempDataProvider(this IMvcCoreBuilder builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); // Ensure the TempData basics are registered. AddViewServices(builder.Services); @@ -89,15 +83,8 @@ public static IMvcCoreBuilder AddViews( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddViews(builder); builder.Services.Configure(setupAction); @@ -119,15 +106,8 @@ public static IMvcCoreBuilder AddCookieTempDataProvider( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); AddCookieTempDataProvider(builder); builder.Services.Configure(setupAction); @@ -145,15 +125,8 @@ public static IMvcCoreBuilder ConfigureViews( this IMvcCoreBuilder builder, Action setupAction) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(setupAction); builder.Services.Configure(setupAction); return builder; diff --git a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewOptionsSetup.cs b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewOptionsSetup.cs index 66a4d07f1a86..e1af4222b2e9 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewOptionsSetup.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DependencyInjection/MvcViewOptionsSetup.cs @@ -21,15 +21,8 @@ public MvcViewOptionsSetup( IOptions dataAnnotationLocalizationOptions, IValidationAttributeAdapterProvider validationAttributeAdapterProvider) { - if (dataAnnotationLocalizationOptions == null) - { - throw new ArgumentNullException(nameof(dataAnnotationLocalizationOptions)); - } - - if (validationAttributeAdapterProvider == null) - { - throw new ArgumentNullException(nameof(validationAttributeAdapterProvider)); - } + ArgumentNullException.ThrowIfNull(dataAnnotationLocalizationOptions); + ArgumentNullException.ThrowIfNull(validationAttributeAdapterProvider); _dataAnnotationsLocalizationOptions = dataAnnotationLocalizationOptions; _validationAttributeAdapterProvider = validationAttributeAdapterProvider; @@ -41,10 +34,7 @@ public MvcViewOptionsSetup( IStringLocalizerFactory stringLocalizerFactory) : this(dataAnnotationOptions, validationAttributeAdapterProvider) { - if (stringLocalizerFactory == null) - { - throw new ArgumentNullException(nameof(stringLocalizerFactory)); - } + ArgumentNullException.ThrowIfNull(stringLocalizerFactory); _stringLocalizerFactory = stringLocalizerFactory; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/DynamicViewData.cs b/src/Mvc/Mvc.ViewFeatures/src/DynamicViewData.cs index 766fea2a6692..443a4558be7c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/DynamicViewData.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/DynamicViewData.cs @@ -11,10 +11,7 @@ internal sealed class DynamicViewData : DynamicObject public DynamicViewData(Func viewDataFunc) { - if (viewDataFunc == null) - { - throw new ArgumentNullException(nameof(viewDataFunc)); - } + ArgumentNullException.ThrowIfNull(viewDataFunc); _viewDataFunc = viewDataFunc; } @@ -43,10 +40,7 @@ public override IEnumerable GetDynamicMemberNames() public override bool TryGetMember(GetMemberBinder binder, out object result) { - if (binder == null) - { - throw new ArgumentNullException(nameof(binder)); - } + ArgumentNullException.ThrowIfNull(binder); result = ViewData[binder.Name]; @@ -57,10 +51,7 @@ public override bool TryGetMember(GetMemberBinder binder, out object result) public override bool TrySetMember(SetMemberBinder binder, object value) { - if (binder == null) - { - throw new ArgumentNullException(nameof(binder)); - } + ArgumentNullException.ThrowIfNull(binder); ViewData[binder.Name] = value; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs b/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs index 976581d90d7e..5858adc33f6f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ExpressionHelper.cs @@ -18,10 +18,7 @@ public static string GetUncachedExpressionText(LambdaExpression expression) public static string GetExpressionText(LambdaExpression expression, ConcurrentDictionary expressionTextCache) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); if (expressionTextCache != null && expressionTextCache.TryGetValue(expression, out var expressionText)) @@ -202,20 +199,9 @@ private static void InsertIndexerInvocationText( Expression indexExpression, LambdaExpression parentExpression) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (indexExpression == null) - { - throw new ArgumentNullException(nameof(indexExpression)); - } - - if (parentExpression == null) - { - throw new ArgumentNullException(nameof(parentExpression)); - } + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(indexExpression); + ArgumentNullException.ThrowIfNull(parentExpression); if (parentExpression.Parameters == null) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/ExpressionMetadataProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/ExpressionMetadataProvider.cs index 850665bf4fff..bb0f30b76a14 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ExpressionMetadataProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ExpressionMetadataProvider.cs @@ -16,15 +16,8 @@ public static ModelExplorer FromLambdaExpression( ViewDataDictionary viewData, IModelMetadataProvider metadataProvider) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(viewData); string propertyName = null; Type containerType = null; @@ -145,10 +138,7 @@ public static ModelExplorer FromStringExpression( ViewDataDictionary viewData, IModelMetadataProvider metadataProvider) { - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } + ArgumentNullException.ThrowIfNull(viewData); var viewDataInfo = ViewDataEvaluator.Eval(viewData, expression); if (viewDataInfo == null) @@ -206,10 +196,7 @@ private static ModelExplorer FromModel( ViewDataDictionary viewData, IModelMetadataProvider metadataProvider) { - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } + ArgumentNullException.ThrowIfNull(viewData); if (viewData.ModelMetadata.ModelType == typeof(object)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/Filters/AutoValidateAntiforgeryTokenAuthorizationFilter.cs b/src/Mvc/Mvc.ViewFeatures/src/Filters/AutoValidateAntiforgeryTokenAuthorizationFilter.cs index a8c0563336eb..31361f167966 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Filters/AutoValidateAntiforgeryTokenAuthorizationFilter.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Filters/AutoValidateAntiforgeryTokenAuthorizationFilter.cs @@ -17,10 +17,7 @@ public AutoValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, protected override bool ShouldValidate(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var method = context.HttpContext.Request.Method; if (HttpMethods.IsGet(method) || diff --git a/src/Mvc/Mvc.ViewFeatures/src/Filters/ControllerSaveTempDataPropertyFilterFactory.cs b/src/Mvc/Mvc.ViewFeatures/src/Filters/ControllerSaveTempDataPropertyFilterFactory.cs index 436d3777953b..3f148ccd7f86 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Filters/ControllerSaveTempDataPropertyFilterFactory.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Filters/ControllerSaveTempDataPropertyFilterFactory.cs @@ -19,10 +19,7 @@ public ControllerSaveTempDataPropertyFilterFactory(IReadOnlyList(); service.Properties = TempDataProperties; diff --git a/src/Mvc/Mvc.ViewFeatures/src/Filters/TempDataApplicationModelProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/Filters/TempDataApplicationModelProvider.cs index 84e0cae3c992..b70cb561c0e3 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Filters/TempDataApplicationModelProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Filters/TempDataApplicationModelProvider.cs @@ -27,10 +27,7 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) /// public void OnProvidersExecuting(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var controllerModel in context.Result.Controllers) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/Filters/ValidateAntiforgeryTokenAuthorizationFilter.cs b/src/Mvc/Mvc.ViewFeatures/src/Filters/ValidateAntiforgeryTokenAuthorizationFilter.cs index 15095473dcfb..709215432755 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Filters/ValidateAntiforgeryTokenAuthorizationFilter.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Filters/ValidateAntiforgeryTokenAuthorizationFilter.cs @@ -14,10 +14,7 @@ internal partial class ValidateAntiforgeryTokenAuthorizationFilter : IAsyncAutho public ValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, ILoggerFactory loggerFactory) { - if (antiforgery == null) - { - throw new ArgumentNullException(nameof(antiforgery)); - } + ArgumentNullException.ThrowIfNull(antiforgery); _antiforgery = antiforgery; _logger = loggerFactory.CreateLogger(GetType()); @@ -25,10 +22,7 @@ public ValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, ILo public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.IsEffectivePolicy(this)) { @@ -52,10 +46,7 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) protected virtual bool ShouldValidate(AuthorizationFilterContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return true; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Filters/ViewDataAttributeApplicationModelProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/Filters/ViewDataAttributeApplicationModelProvider.cs index 86632f4d39c9..d4ca9a141919 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Filters/ViewDataAttributeApplicationModelProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Filters/ViewDataAttributeApplicationModelProvider.cs @@ -19,10 +19,7 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) /// public void OnProvidersExecuting(ApplicationModelProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var controllerModel in context.Result.Controllers) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/FormContext.cs b/src/Mvc/Mvc.ViewFeatures/src/FormContext.cs index d6f78f1e278c..46e75b41f4d6 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/FormContext.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/FormContext.cs @@ -132,10 +132,7 @@ private Dictionary InvariantFields /// public bool RenderedField(string fieldName) { - if (fieldName == null) - { - throw new ArgumentNullException(nameof(fieldName)); - } + ArgumentNullException.ThrowIfNull(fieldName); bool result; RenderedFields.TryGetValue(fieldName, out result); @@ -151,10 +148,7 @@ public bool RenderedField(string fieldName) /// If true, the given has been rendered. public void RenderedField(string fieldName, bool value) { - if (fieldName == null) - { - throw new ArgumentNullException(nameof(fieldName)); - } + ArgumentNullException.ThrowIfNull(fieldName); RenderedFields[fieldName] = value; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelper.cs b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelper.cs index da2653fad4ea..3c957e883d5c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelper.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelper.cs @@ -66,35 +66,12 @@ public HtmlHelper( HtmlEncoder htmlEncoder, UrlEncoder urlEncoder) { - if (htmlGenerator == null) - { - throw new ArgumentNullException(nameof(htmlGenerator)); - } - - if (viewEngine == null) - { - throw new ArgumentNullException(nameof(viewEngine)); - } - - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (bufferScope == null) - { - throw new ArgumentNullException(nameof(bufferScope)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (urlEncoder == null) - { - throw new ArgumentNullException(nameof(urlEncoder)); - } + ArgumentNullException.ThrowIfNull(htmlGenerator); + ArgumentNullException.ThrowIfNull(viewEngine); + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(bufferScope); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(urlEncoder); _viewEngine = viewEngine; _htmlGenerator = htmlGenerator; @@ -203,10 +180,7 @@ public static IDictionary AnonymousObjectToHtmlAttributes(object /// The context to use. public virtual void Contextualize(ViewContext viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); ViewContext = viewContext; } @@ -222,10 +196,7 @@ public IHtmlContent ActionLink( object routeValues, object htmlAttributes) { - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(linkText); var tagBuilder = _htmlGenerator.GenerateActionLink( ViewContext, @@ -325,10 +296,7 @@ public string FormatValue(object value, string format) /// public string GenerateIdFromName(string fullName) { - if (fullName == null) - { - throw new ArgumentNullException(nameof(fullName)); - } + ArgumentNullException.ThrowIfNull(fullName); return NameAndIdProvider.CreateSanitizedId(ViewContext, fullName, IdAttributeDotReplacement); } @@ -414,10 +382,7 @@ public IEnumerable GetEnumSelectList() where TEnum : stru /// public IEnumerable GetEnumSelectList(Type enumType) { - if (enumType == null) - { - throw new ArgumentNullException(nameof(enumType)); - } + ArgumentNullException.ThrowIfNull(enumType); var metadata = MetadataProvider.GetMetadataForType(enumType); if (!metadata.IsEnum || metadata.IsFlagsEnum) @@ -482,10 +447,7 @@ public async Task PartialAsync( object model, ViewDataDictionary viewData) { - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(partialViewName); var viewBuffer = new ViewBuffer(_bufferScope, partialViewName, ViewBuffer.PartialViewPageSize); using (var writer = new ViewBufferTextWriter(viewBuffer, Encoding.UTF8)) @@ -498,10 +460,7 @@ public async Task PartialAsync( /// public Task RenderPartialAsync(string partialViewName, object model, ViewDataDictionary viewData) { - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(partialViewName); return RenderPartialCoreAsync(partialViewName, model, viewData, ViewContext.Writer); } @@ -548,10 +507,7 @@ protected virtual async Task RenderPartialCoreAsync( ViewDataDictionary viewData, TextWriter writer) { - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(partialViewName); var viewEngineResult = _viewEngine.GetView( ViewContext.ExecutingFilePath, @@ -637,10 +593,7 @@ public IHtmlContent RouteLink( object routeValues, object htmlAttributes) { - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(linkText); var tagBuilder = _htmlGenerator.GenerateRouteLink( ViewContext, @@ -815,10 +768,7 @@ protected virtual IHtmlContent GenerateCheckBox( /// The display name. protected virtual string GenerateDisplayName(ModelExplorer modelExplorer, string expression) { - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(modelExplorer); // We don't call ModelMetadata.GetDisplayName here because // we want to fall back to the field name rather than the ModelType. @@ -1092,10 +1042,7 @@ protected virtual IHtmlContent GenerateLabel( string labelText, object htmlAttributes) { - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(modelExplorer); var tagBuilder = _htmlGenerator.GenerateLabel( ViewContext, @@ -1420,10 +1367,7 @@ protected virtual string GenerateValue(string expression, object value, string f /// protected virtual IEnumerable GetEnumSelectList(ModelMetadata metadata) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadata); if (!metadata.IsEnum || metadata.IsFlagsEnum) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOfT.cs b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOfT.cs index 575fc7f37684..045eb38ddf09 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOfT.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOfT.cs @@ -47,10 +47,7 @@ public HtmlHelper( /// public override void Contextualize(ViewContext viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); if (viewContext.ViewData == null) { @@ -95,10 +92,7 @@ public IHtmlContent CheckBoxFor( Expression> expression, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateCheckBox( @@ -115,10 +109,7 @@ public IHtmlContent DropDownListFor( string optionLabel, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateDropDown( @@ -136,10 +127,7 @@ public IHtmlContent DisplayFor( string htmlFieldName, object additionalViewData) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateDisplay( @@ -152,10 +140,7 @@ public IHtmlContent DisplayFor( /// public string DisplayNameFor(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateDisplayName(modelExpression.ModelExplorer, modelExpression.Name); @@ -165,10 +150,7 @@ public string DisplayNameFor(Expression> expressi public string DisplayNameForInnerType( Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = _modelExpressionProvider.CreateModelExpression( new ViewDataDictionary(ViewData, model: null), @@ -180,10 +162,7 @@ public string DisplayNameForInnerType( /// public string DisplayTextFor(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); return GenerateDisplayText(GetModelExplorer(expression)); } @@ -195,10 +174,7 @@ public IHtmlContent EditorFor( string htmlFieldName, object additionalViewData) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateEditor( @@ -213,10 +189,7 @@ public IHtmlContent HiddenFor( Expression> expression, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateHidden( @@ -230,10 +203,7 @@ public IHtmlContent HiddenFor( /// public string IdFor(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); return GenerateId(GetExpressionName(expression)); } @@ -244,10 +214,7 @@ public IHtmlContent LabelFor( string labelText, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateLabel(modelExpression.ModelExplorer, modelExpression.Name, labelText, htmlAttributes); @@ -259,10 +226,7 @@ public IHtmlContent ListBoxFor( IEnumerable selectList, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); var name = modelExpression.Name; @@ -273,10 +237,7 @@ public IHtmlContent ListBoxFor( /// public string NameFor(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var expressionName = GetExpressionName(expression); return Name(expressionName); @@ -287,10 +248,7 @@ public IHtmlContent PasswordFor( Expression> expression, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GeneratePassword( @@ -306,15 +264,8 @@ public IHtmlContent RadioButtonFor( object value, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(value); var modelExpression = GetModelExpression(expression); return GenerateRadioButton( @@ -332,10 +283,7 @@ public IHtmlContent TextAreaFor( int columns, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateTextArea(modelExpression.ModelExplorer, modelExpression.Name, rows, columns, htmlAttributes); @@ -347,10 +295,7 @@ public IHtmlContent TextBoxFor( string format, object htmlAttributes) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateTextBox( @@ -373,10 +318,7 @@ private ModelExpression GetModelExpression(ExpressionThe expression name. protected string GetExpressionName(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); return _modelExpressionProvider.GetExpressionText(expression); } @@ -389,10 +331,7 @@ protected string GetExpressionName(Expression> ex /// The . protected ModelExplorer GetModelExplorer(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return modelExpression.ModelExplorer; @@ -405,10 +344,7 @@ public IHtmlContent ValidationMessageFor( object htmlAttributes, string tag) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateValidationMessage( @@ -422,10 +358,7 @@ public IHtmlContent ValidationMessageFor( /// public string ValueFor(Expression> expression, string format) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); var modelExpression = GetModelExpression(expression); return GenerateValue(modelExpression.Name, modelExpression.Model, format, useViewData: false); diff --git a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOptions.cs b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOptions.cs index d4ce05f2811f..e67670965035 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOptions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/HtmlHelperOptions.cs @@ -30,10 +30,7 @@ public string IdAttributeDotReplacement get => _idAttributeDotReplacement; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _idAttributeDotReplacement = value; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs index db8290bbadc6..840b19288574 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Infrastructure/DefaultTempDataSerializer.cs @@ -10,10 +10,7 @@ internal sealed class DefaultTempDataSerializer : TempDataSerializer { public override IDictionary Deserialize(byte[] value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length == 0) { @@ -219,10 +216,7 @@ public override byte[] Serialize(IDictionary values) public override bool CanSerializeType(Type type) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } + ArgumentNullException.ThrowIfNull(type); type = Nullable.GetUnderlyingType(type) ?? type; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelExplorer.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelExplorer.cs index 86804b6f9786..9ad98bf3bebb 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelExplorer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelExplorer.cs @@ -30,15 +30,8 @@ public ModelExplorer( ModelMetadata metadata, object model) { - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(metadata); _metadataProvider = metadataProvider; Metadata = metadata; @@ -58,20 +51,9 @@ public ModelExplorer( ModelMetadata metadata, Func modelAccessor) { - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(container); + ArgumentNullException.ThrowIfNull(metadata); _metadataProvider = metadataProvider; Container = container; @@ -92,15 +74,8 @@ public ModelExplorer( ModelMetadata metadata, object model) { - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(metadata); _metadataProvider = metadataProvider; Container = container; @@ -258,10 +233,7 @@ public ModelExplorer GetExplorerForModel(object model) /// A , or null. public ModelExplorer GetExplorerForProperty(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); for (var i = 0; i < PropertiesInternal.Length; i++) { @@ -287,10 +259,7 @@ public ModelExplorer GetExplorerForProperty(string name) /// public ModelExplorer GetExplorerForProperty(string name, Func modelAccessor) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var metadata = GetMetadataForRuntimeType(); @@ -315,10 +284,7 @@ public ModelExplorer GetExplorerForProperty(string name, Func mo /// public ModelExplorer GetExplorerForProperty(string name, object model) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var metadata = GetMetadataForRuntimeType(); @@ -349,10 +315,7 @@ public ModelExplorer GetExplorerForProperty(string name, object model) /// public ModelExplorer GetExplorerForExpression(Type modelType, object model) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var metadata = _metadataProvider.GetMetadataForType(modelType); return GetExplorerForExpression(metadata, model); @@ -377,10 +340,7 @@ public ModelExplorer GetExplorerForExpression(Type modelType, object model) /// public ModelExplorer GetExplorerForExpression(ModelMetadata metadata, object model) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadata); return new ModelExplorer(_metadataProvider, this, metadata, model); } @@ -404,10 +364,7 @@ public ModelExplorer GetExplorerForExpression(ModelMetadata metadata, object mod /// public ModelExplorer GetExplorerForExpression(Type modelType, Func modelAccessor) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var metadata = _metadataProvider.GetMetadataForType(modelType); return GetExplorerForExpression(metadata, modelAccessor); @@ -432,10 +389,7 @@ public ModelExplorer GetExplorerForExpression(Type modelType, Func public ModelExplorer GetExplorerForExpression(ModelMetadata metadata, Func modelAccessor) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(metadata); return new ModelExplorer(_metadataProvider, this, metadata, modelAccessor); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelExplorerExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelExplorerExtensions.cs index dbca901f0187..40d620ab3e62 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelExplorerExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelExplorerExtensions.cs @@ -28,10 +28,7 @@ public static class ModelExplorerExtensions /// public static string GetSimpleDisplayText(this ModelExplorer modelExplorer) { - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(modelExplorer); if (modelExplorer.Metadata.SimpleDisplayProperty != null) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelExpression.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelExpression.cs index eaea11668822..8f350c5ebe13 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelExpression.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelExpression.cs @@ -21,15 +21,8 @@ public sealed class ModelExpression /// public ModelExpression(string name, ModelExplorer modelExplorer) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(modelExplorer); Name = name; ModelExplorer = modelExplorer; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelExpressionProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelExpressionProvider.cs index 164a3c52223a..5eb0a98fb61c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelExpressionProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelExpressionProvider.cs @@ -21,10 +21,7 @@ public class ModelExpressionProvider : IModelExpressionProvider /// The . public ModelExpressionProvider(IModelMetadataProvider modelMetadataProvider) { - if (modelMetadataProvider == null) - { - throw new ArgumentNullException(nameof(modelMetadataProvider)); - } + ArgumentNullException.ThrowIfNull(modelMetadataProvider); _modelMetadataProvider = modelMetadataProvider; _expressionTextCache = new ConcurrentDictionary(LambdaExpressionComparer.Instance); @@ -39,10 +36,7 @@ public ModelExpressionProvider(IModelMetadataProvider modelMetadataProvider) /// The expression name. public string GetExpressionText(Expression> expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); return ExpressionHelper.GetExpressionText(expression, _expressionTextCache); } @@ -52,15 +46,8 @@ public ModelExpression CreateModelExpression( ViewDataDictionary viewData, Expression> expression) { - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(viewData); + ArgumentNullException.ThrowIfNull(expression); var name = GetExpressionText(expression); var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, viewData, _modelMetadataProvider); @@ -85,15 +72,8 @@ public ModelExpression CreateModelExpression( ViewDataDictionary viewData, string expression) { - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(viewData); + ArgumentNullException.ThrowIfNull(expression); var modelExplorer = ExpressionMetadataProvider.FromStringExpression(expression, viewData, _modelMetadataProvider); if (modelExplorer == null) diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelMetadataProviderExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelMetadataProviderExtensions.cs index 16d46e8cbaf2..229dd50e9f91 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelMetadataProviderExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelMetadataProviderExtensions.cs @@ -25,15 +25,8 @@ public static ModelExplorer GetModelExplorerForType( Type modelType, object model) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(modelType); var modelMetadata = provider.GetMetadataForType(modelType); return new ModelExplorer(provider, modelMetadata, model); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ModelStateDictionaryExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/ModelStateDictionaryExtensions.cs index 7c7e1ad4dac2..62799e105f02 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ModelStateDictionaryExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ModelStateDictionaryExtensions.cs @@ -27,20 +27,9 @@ public static void AddModelError( Expression> expression, string errorMessage) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (errorMessage == null) - { - throw new ArgumentNullException(nameof(errorMessage)); - } + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(errorMessage); modelState.AddModelError(GetExpressionText(expression), errorMessage); } @@ -65,15 +54,8 @@ public static void TryAddModelException( Expression> expression, Exception exception) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(expression); modelState.TryAddModelException(GetExpressionText(expression), exception); } @@ -95,20 +77,9 @@ public static void AddModelError( Exception exception, ModelMetadata metadata) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(metadata); modelState.AddModelError(GetExpressionText(expression), exception, metadata); } @@ -127,15 +98,8 @@ public static bool Remove( this ModelStateDictionary modelState, Expression> expression) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(expression); return modelState.Remove(GetExpressionText(expression)); } @@ -151,15 +115,8 @@ public static void RemoveAll( this ModelStateDictionary modelState, Expression> expression) { - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(expression); string modelKey = GetExpressionText(expression); if (string.IsNullOrEmpty(modelKey)) diff --git a/src/Mvc/Mvc.ViewFeatures/src/MvcViewOptions.cs b/src/Mvc/Mvc.ViewFeatures/src/MvcViewOptions.cs index b2b9a85cb0d0..fa72c64f1c6a 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/MvcViewOptions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/MvcViewOptions.cs @@ -27,10 +27,7 @@ public HtmlHelperOptions HtmlHelperOptions get => _htmlHelperOptions; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _htmlHelperOptions = value; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/NameAndIdProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/NameAndIdProvider.cs index 32013db340ea..827561b69de2 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/NameAndIdProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/NameAndIdProvider.cs @@ -31,15 +31,8 @@ internal static class NameAndIdProvider /// public static string CreateSanitizedId(ViewContext viewContext, string fullName, string invalidCharReplacement) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (invalidCharReplacement == null) - { - throw new ArgumentNullException(nameof(invalidCharReplacement)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(invalidCharReplacement); if (string.IsNullOrEmpty(fullName)) { @@ -101,20 +94,9 @@ public static void GenerateId( string fullName, string invalidCharReplacement) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (tagBuilder == null) - { - throw new ArgumentNullException(nameof(tagBuilder)); - } - - if (invalidCharReplacement == null) - { - throw new ArgumentNullException(nameof(invalidCharReplacement)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(tagBuilder); + ArgumentNullException.ThrowIfNull(invalidCharReplacement); if (string.IsNullOrEmpty(fullName)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/NullView.cs b/src/Mvc/Mvc.ViewFeatures/src/NullView.cs index 3d8c32783f17..78c3a1ab7e1d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/NullView.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/NullView.cs @@ -14,10 +14,7 @@ internal sealed class NullView : IView public Task RenderAsync(ViewContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return Task.CompletedTask; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/PageRemoteAttribute.cs b/src/Mvc/Mvc.ViewFeatures/src/PageRemoteAttribute.cs index 4f6c9cb78d50..01d19b04aeeb 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/PageRemoteAttribute.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/PageRemoteAttribute.cs @@ -38,10 +38,7 @@ public class PageRemoteAttribute : RemoteAttributeBase /// protected override string GetUrl(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var services = context.ActionContext.HttpContext.RequestServices; var factory = services.GetRequiredService(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/PartialViewResult.cs b/src/Mvc/Mvc.ViewFeatures/src/PartialViewResult.cs index 59a0b338a018..c9185fc54155 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/PartialViewResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/PartialViewResult.cs @@ -59,10 +59,7 @@ public class PartialViewResult : ActionResult, IStatusCodeActionResult /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var services = context.HttpContext.RequestServices; var executor = services.GetService>(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/PartialViewResultExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/PartialViewResultExecutor.cs index 4a05f8281694..13d5e67744ce 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/PartialViewResultExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/PartialViewResultExecutor.cs @@ -42,10 +42,7 @@ public PartialViewResultExecutor( IModelMetadataProvider modelMetadataProvider) : base(viewOptions, writerFactory, viewEngine, tempDataFactory, diagnosticListener, modelMetadataProvider) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); Logger = loggerFactory.CreateLogger(); } @@ -63,15 +60,8 @@ public PartialViewResultExecutor( /// A . public virtual ViewEngineResult FindView(ActionContext actionContext, PartialViewResult viewResult) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (viewResult == null) - { - throw new ArgumentNullException(nameof(viewResult)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(viewResult); var viewEngine = viewResult.ViewEngine ?? ViewEngine; var viewName = viewResult.ViewName ?? GetActionName(actionContext) ?? string.Empty; @@ -138,20 +128,9 @@ public virtual ViewEngineResult FindView(ActionContext actionContext, PartialVie /// A which will complete when view execution is completed. public virtual Task ExecuteAsync(ActionContext actionContext, IView view, PartialViewResult viewResult) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (view == null) - { - throw new ArgumentNullException(nameof(view)); - } - - if (viewResult == null) - { - throw new ArgumentNullException(nameof(viewResult)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(viewResult); return ExecuteAsync( actionContext, @@ -165,15 +144,8 @@ public virtual Task ExecuteAsync(ActionContext actionContext, IView view, Partia /// public virtual async Task ExecuteAsync(ActionContext context, PartialViewResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var stopwatch = ValueStopwatch.StartNew(); @@ -191,10 +163,7 @@ public virtual async Task ExecuteAsync(ActionContext context, PartialViewResult private static string? GetActionName(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.RouteData.Values.TryGetValue(ActionNameKey, out var routeValue)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/ComponentRenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/ComponentRenderer.cs index 8ff7c8af3c9f..cdaf028a0e0b 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/ComponentRenderer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/ComponentRenderer.cs @@ -34,15 +34,8 @@ public async ValueTask RenderComponentAsync( RenderMode renderMode, object parameters) { - if (viewContext is null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(componentType); if (!typeof(IComponent).IsAssignableFrom(componentType)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttribute.cs b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttribute.cs index df55687adae2..fa98afaf73d9 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttribute.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttribute.cs @@ -106,10 +106,7 @@ public RemoteAttribute(string action, string controller, string areaName) /// protected override string GetUrl(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var services = context.ActionContext.HttpContext.RequestServices; var factory = services.GetRequiredService(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs index 04af5a9120ce..326b63ee5d5c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/RemoteAttributeBase.cs @@ -146,10 +146,7 @@ public override bool IsValid(object? value) /// public virtual void AddValidation(ClientModelValidationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); MergeAttribute(context.Attributes, "data-val", "true"); diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperComponentExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperComponentExtensions.cs index e960f7c17c0c..7fd853f949b0 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperComponentExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperComponentExtensions.cs @@ -50,15 +50,8 @@ public static async Task RenderComponentAsync( RenderMode renderMode, object parameters) { - if (htmlHelper is null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (componentType is null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(componentType); var viewContext = htmlHelper.ViewContext; var componentRenderer = viewContext.HttpContext.RequestServices.GetRequiredService(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayExtensions.cs index 9b34f040a654..2caba058a1cb 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayExtensions.cs @@ -37,10 +37,7 @@ public static class HtmlHelperDisplayExtensions /// public static IHtmlContent Display(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display(expression, templateName: null, htmlFieldName: null, additionalViewData: null); } @@ -80,10 +77,7 @@ public static IHtmlContent Display( string expression, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression, @@ -123,10 +117,7 @@ public static IHtmlContent Display( string expression, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display(expression, templateName, htmlFieldName: null, additionalViewData: null); } @@ -168,10 +159,7 @@ public static IHtmlContent Display( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression, @@ -216,10 +204,7 @@ public static IHtmlContent Display( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display(expression, templateName, htmlFieldName, additionalViewData: null); } @@ -247,15 +232,8 @@ public static IHtmlContent DisplayFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayFor( expression, @@ -294,15 +272,8 @@ public static IHtmlContent DisplayFor( Expression> expression, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayFor( expression, @@ -337,15 +308,8 @@ public static IHtmlContent DisplayFor( Expression> expression, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayFor( expression, @@ -386,15 +350,8 @@ public static IHtmlContent DisplayFor( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayFor( expression, @@ -434,15 +391,8 @@ public static IHtmlContent DisplayFor( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayFor( expression, @@ -469,10 +419,7 @@ public static IHtmlContent DisplayFor( /// public static IHtmlContent DisplayForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, @@ -504,10 +451,7 @@ public static IHtmlContent DisplayForModel(this IHtmlHelper htmlHelper) /// public static IHtmlContent DisplayForModel(this IHtmlHelper htmlHelper, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, @@ -535,10 +479,7 @@ public static IHtmlContent DisplayForModel(this IHtmlHelper htmlHelper, object a /// public static IHtmlContent DisplayForModel(this IHtmlHelper htmlHelper, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, @@ -575,10 +516,7 @@ public static IHtmlContent DisplayForModel( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, @@ -614,10 +552,7 @@ public static IHtmlContent DisplayForModel( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, @@ -659,10 +594,7 @@ public static IHtmlContent DisplayForModel( string htmlFieldName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Display( expression: null, diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayNameExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayNameExtensions.cs index cddc49ed629c..701f11bb493e 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayNameExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperDisplayNameExtensions.cs @@ -17,10 +17,7 @@ public static class HtmlHelperDisplayNameExtensions /// A containing the display name. public static string DisplayNameForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DisplayName(expression: null); } @@ -40,15 +37,8 @@ public static string DisplayNameFor( this IHtmlHelper> htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DisplayNameForInnerType(expression); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperEditorExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperEditorExtensions.cs index 946a72d08181..34950c1c443f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperEditorExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperEditorExtensions.cs @@ -37,10 +37,7 @@ public static class HtmlHelperEditorExtensions /// public static IHtmlContent Editor(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor(expression, templateName: null, htmlFieldName: null, additionalViewData: null); } @@ -80,10 +77,7 @@ public static IHtmlContent Editor( string expression, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression, @@ -120,10 +114,7 @@ public static IHtmlContent Editor( /// public static IHtmlContent Editor(this IHtmlHelper htmlHelper, string expression, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor(expression, templateName, htmlFieldName: null, additionalViewData: null); } @@ -165,10 +156,7 @@ public static IHtmlContent Editor( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression, @@ -213,10 +201,7 @@ public static IHtmlContent Editor( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor(expression, templateName, htmlFieldName, additionalViewData: null); } @@ -244,15 +229,8 @@ public static IHtmlContent EditorFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.EditorFor(expression, templateName: null, htmlFieldName: null, additionalViewData: null); } @@ -287,15 +265,8 @@ public static IHtmlContent EditorFor( Expression> expression, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.EditorFor( expression, @@ -330,15 +301,8 @@ public static IHtmlContent EditorFor( Expression> expression, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.EditorFor(expression, templateName, htmlFieldName: null, additionalViewData: null); } @@ -375,15 +339,8 @@ public static IHtmlContent EditorFor( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.EditorFor( expression, @@ -423,15 +380,8 @@ public static IHtmlContent EditorFor( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.EditorFor(expression, templateName, htmlFieldName, additionalViewData: null); } @@ -454,10 +404,7 @@ public static IHtmlContent EditorFor( /// public static IHtmlContent EditorForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, @@ -489,10 +436,7 @@ public static IHtmlContent EditorForModel(this IHtmlHelper htmlHelper) /// public static IHtmlContent EditorForModel(this IHtmlHelper htmlHelper, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, @@ -520,10 +464,7 @@ public static IHtmlContent EditorForModel(this IHtmlHelper htmlHelper, object ad /// public static IHtmlContent EditorForModel(this IHtmlHelper htmlHelper, string templateName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, @@ -560,10 +501,7 @@ public static IHtmlContent EditorForModel( string templateName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, @@ -599,10 +537,7 @@ public static IHtmlContent EditorForModel( string templateName, string htmlFieldName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, @@ -644,10 +579,7 @@ public static IHtmlContent EditorForModel( string htmlFieldName, object additionalViewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Editor( expression: null, diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperFormExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperFormExtensions.cs index 43751350995f..a3f530131edc 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperFormExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperFormExtensions.cs @@ -21,10 +21,7 @@ public static class HtmlHelperFormExtensions /// public static MvcForm BeginForm(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); // Generates
. return htmlHelper.BeginForm( @@ -54,10 +51,7 @@ public static MvcForm BeginForm(this IHtmlHelper htmlHelper) /// public static MvcForm BeginForm(this IHtmlHelper htmlHelper, bool? antiforgery) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); // Generates . return htmlHelper.BeginForm( @@ -83,10 +77,7 @@ public static MvcForm BeginForm(this IHtmlHelper htmlHelper, bool? antiforgery) /// public static MvcForm BeginForm(this IHtmlHelper htmlHelper, FormMethod method) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName: null, @@ -119,10 +110,7 @@ public static MvcForm BeginForm( FormMethod method, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName: null, @@ -162,10 +150,7 @@ public static MvcForm BeginForm( bool? antiforgery, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName: null, @@ -196,10 +181,7 @@ public static MvcForm BeginForm( /// public static MvcForm BeginForm(this IHtmlHelper htmlHelper, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName: null, @@ -228,10 +210,7 @@ public static MvcForm BeginForm( string actionName, string controllerName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName, @@ -268,10 +247,7 @@ public static MvcForm BeginForm( string controllerName, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName, @@ -302,10 +278,7 @@ public static MvcForm BeginForm( string controllerName, FormMethod method) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName, @@ -344,10 +317,7 @@ public static MvcForm BeginForm( object routeValues, FormMethod method) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName, @@ -384,10 +354,7 @@ public static MvcForm BeginForm( FormMethod method, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginForm( actionName, @@ -418,10 +385,7 @@ public static MvcForm BeginForm( /// public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName: null, @@ -456,10 +420,7 @@ public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeVa /// public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeValues, bool? antiforgery) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName: null, @@ -483,10 +444,7 @@ public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, object routeVa /// public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, string routeName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, @@ -515,10 +473,7 @@ public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, string routeNa /// public static MvcForm BeginRouteForm(this IHtmlHelper htmlHelper, string routeName, bool? antiforgery) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, @@ -552,10 +507,7 @@ public static MvcForm BeginRouteForm( string routeName, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, @@ -583,10 +535,7 @@ public static MvcForm BeginRouteForm( string routeName, FormMethod method) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, @@ -622,10 +571,7 @@ public static MvcForm BeginRouteForm( object routeValues, FormMethod method) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, @@ -659,10 +605,7 @@ public static MvcForm BeginRouteForm( FormMethod method, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.BeginRouteForm( routeName, diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperInputExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperInputExtensions.cs index 45faa1db3bb9..762dce236445 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperInputExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperInputExtensions.cs @@ -30,10 +30,7 @@ public static class HtmlHelperInputExtensions /// public static IHtmlContent CheckBox(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.CheckBox(expression, isChecked: null, htmlAttributes: null); } @@ -62,10 +59,7 @@ public static IHtmlContent CheckBox( string expression, bool isChecked) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.CheckBox(expression, isChecked, htmlAttributes: null); } @@ -98,10 +92,7 @@ public static IHtmlContent CheckBox( string expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.CheckBox(expression, isChecked: null, htmlAttributes: htmlAttributes); } @@ -126,15 +117,8 @@ public static IHtmlContent CheckBoxFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.CheckBoxFor(expression, htmlAttributes: null); } @@ -157,10 +141,7 @@ public static IHtmlContent CheckBoxFor( /// public static IHtmlContent Hidden(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Hidden(expression, value: null, htmlAttributes: null); } @@ -188,10 +169,7 @@ public static IHtmlContent Hidden( string expression, object value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Hidden(expression, value, htmlAttributes: null); } @@ -217,15 +195,8 @@ public static IHtmlContent HiddenFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.HiddenFor(expression, htmlAttributes: null); } @@ -244,10 +215,7 @@ public static IHtmlContent HiddenFor( /// public static IHtmlContent Password(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Password(expression, value: null, htmlAttributes: null); } @@ -270,10 +238,7 @@ public static IHtmlContent Password( string expression, object value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Password(expression, value, htmlAttributes: null); } @@ -296,15 +261,8 @@ public static IHtmlContent PasswordFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.PasswordFor(expression, htmlAttributes: null); } @@ -334,10 +292,7 @@ public static IHtmlContent RadioButton( string expression, object value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.RadioButton(expression, value, isChecked: null, htmlAttributes: null); } @@ -378,10 +333,7 @@ public static IHtmlContent RadioButton( object value, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.RadioButton(expression, value, isChecked: null, htmlAttributes: htmlAttributes); } @@ -420,10 +372,7 @@ public static IHtmlContent RadioButton( object value, bool isChecked) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.RadioButton(expression, value, isChecked, htmlAttributes: null); } @@ -454,20 +403,9 @@ public static IHtmlContent RadioButtonFor( Expression> expression, object value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(value); return htmlHelper.RadioButtonFor(expression, value, htmlAttributes: null); } @@ -490,10 +428,7 @@ public static IHtmlContent RadioButtonFor( /// public static IHtmlContent TextBox(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextBox(expression, value: null, format: null, htmlAttributes: null); } @@ -521,10 +456,7 @@ public static IHtmlContent TextBox( string expression, object value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextBox(expression, value, format: null, htmlAttributes: null); } @@ -557,10 +489,7 @@ public static IHtmlContent TextBox( object value, string format) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextBox(expression, value, format, htmlAttributes: null); } @@ -595,10 +524,7 @@ public static IHtmlContent TextBox( object value, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextBox(expression, value, format: null, htmlAttributes: htmlAttributes); } @@ -624,15 +550,8 @@ public static IHtmlContent TextBoxFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: null); } @@ -663,15 +582,8 @@ public static IHtmlContent TextBoxFor( Expression> expression, string format) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.TextBoxFor(expression, format, htmlAttributes: null); } @@ -704,15 +616,8 @@ public static IHtmlContent TextBoxFor( Expression> expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: htmlAttributes); } @@ -737,10 +642,7 @@ public static IHtmlContent TextArea( this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextArea(expression, value: null, rows: 0, columns: 0, htmlAttributes: null); } @@ -771,10 +673,7 @@ public static IHtmlContent TextArea( string expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextArea(expression, value: null, rows: 0, columns: 0, htmlAttributes: htmlAttributes); } @@ -802,10 +701,7 @@ public static IHtmlContent TextArea( string expression, string value) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextArea(expression, value, rows: 0, columns: 0, htmlAttributes: null); } @@ -839,10 +735,7 @@ public static IHtmlContent TextArea( string value, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.TextArea(expression, value, rows: 0, columns: 0, htmlAttributes: htmlAttributes); } @@ -868,15 +761,8 @@ public static IHtmlContent TextAreaFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.TextAreaFor(expression, rows: 0, columns: 0, htmlAttributes: null); } @@ -908,15 +794,8 @@ public static IHtmlContent TextAreaFor( Expression> expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.TextAreaFor(expression, rows: 0, columns: 0, htmlAttributes: htmlAttributes); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLabelExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLabelExtensions.cs index fd99d5c9a466..4cbf83fc9a64 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLabelExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLabelExtensions.cs @@ -19,10 +19,7 @@ public static class HtmlHelperLabelExtensions /// A new containing the <label> element. public static IHtmlContent Label(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression, labelText: null, htmlAttributes: null); } @@ -36,10 +33,7 @@ public static IHtmlContent Label(this IHtmlHelper htmlHelper, string expression) /// A new containing the <label> element. public static IHtmlContent Label(this IHtmlHelper htmlHelper, string expression, string labelText) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression, labelText, htmlAttributes: null); } @@ -56,15 +50,8 @@ public static IHtmlContent LabelFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.LabelFor(expression, labelText: null, htmlAttributes: null); } @@ -83,15 +70,8 @@ public static IHtmlContent LabelFor( Expression> expression, string labelText) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.LabelFor(expression, labelText, htmlAttributes: null); } @@ -114,15 +94,8 @@ public static IHtmlContent LabelFor( Expression> expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.LabelFor(expression, labelText: null, htmlAttributes: htmlAttributes); } @@ -134,10 +107,7 @@ public static IHtmlContent LabelFor( /// A new containing the <label> element. public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression: null, labelText: null, htmlAttributes: null); } @@ -150,10 +120,7 @@ public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper) /// A new containing the <label> element. public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper, string labelText) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression: null, labelText: labelText, htmlAttributes: null); } @@ -170,10 +137,7 @@ public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper, string lab /// A new containing the <label> element. public static IHtmlContent LabelForModel(this IHtmlHelper htmlHelper, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression: null, labelText: null, htmlAttributes: htmlAttributes); } @@ -194,10 +158,7 @@ public static IHtmlContent LabelForModel( string labelText, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Label(expression: null, labelText: labelText, htmlAttributes: htmlAttributes); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLinkExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLinkExtensions.cs index 773c5e80bead..6dc081f51503 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLinkExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperLinkExtensions.cs @@ -22,15 +22,8 @@ public static IHtmlContent ActionLink( string linkText, string actionName) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -63,15 +56,8 @@ public static IHtmlContent ActionLink( string actionName, object routeValues) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -110,15 +96,8 @@ public static IHtmlContent ActionLink( object routeValues, object htmlAttributes) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -145,15 +124,8 @@ public static IHtmlContent ActionLink( string actionName, string controllerName) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -188,15 +160,8 @@ public static IHtmlContent ActionLink( string controllerName, object routeValues) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -237,15 +202,8 @@ public static IHtmlContent ActionLink( object routeValues, object htmlAttributes) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(helper); + ArgumentNullException.ThrowIfNull(linkText); return helper.ActionLink( linkText, @@ -276,15 +234,8 @@ public static IHtmlContent RouteLink( string linkText, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(linkText); return htmlHelper.RouteLink( linkText, @@ -308,15 +259,8 @@ public static IHtmlContent RouteLink( string linkText, string routeName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(linkText); return htmlHelper.RouteLink( linkText, @@ -348,15 +292,8 @@ public static IHtmlContent RouteLink( string routeName, object routeValues) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(linkText); return htmlHelper.RouteLink( linkText, @@ -392,15 +329,8 @@ public static IHtmlContent RouteLink( object routeValues, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(linkText); return htmlHelper.RouteLink( linkText, @@ -438,15 +368,8 @@ public static IHtmlContent RouteLink( object routeValues, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (linkText == null) - { - throw new ArgumentNullException(nameof(linkText)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(linkText); return htmlHelper.RouteLink( linkText, diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperNameExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperNameExtensions.cs index cfe3f2ddb1bc..6ee5dfe09199 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperNameExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperNameExtensions.cs @@ -17,10 +17,7 @@ public static class HtmlHelperNameExtensions /// A containing the element name. public static string NameForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Name(expression: null); } @@ -32,10 +29,7 @@ public static string NameForModel(this IHtmlHelper htmlHelper) /// A containing the element Id. public static string IdForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Id(expression: null); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperPartialExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperPartialExtensions.cs index a9877de8b44c..771df09f93ec 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperPartialExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperPartialExtensions.cs @@ -26,15 +26,8 @@ public static Task PartialAsync( this IHtmlHelper htmlHelper, string partialViewName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.PartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData: null); } @@ -56,15 +49,8 @@ public static Task PartialAsync( string partialViewName, ViewDataDictionary viewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.PartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData); } @@ -86,15 +72,8 @@ public static Task PartialAsync( string partialViewName, object model) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.PartialAsync(partialViewName, model, viewData: null); } @@ -183,15 +162,8 @@ public static IHtmlContent Partial( object model, ViewDataDictionary viewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); var result = htmlHelper.PartialAsync(partialViewName, model, viewData); return result.GetAwaiter().GetResult(); @@ -265,15 +237,8 @@ public static void RenderPartial( object model, ViewDataDictionary viewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); var result = htmlHelper.RenderPartialAsync(partialViewName, model, viewData); result.GetAwaiter().GetResult(); @@ -294,15 +259,8 @@ public static Task RenderPartialAsync( this IHtmlHelper htmlHelper, string partialViewName) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.RenderPartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData: null); } @@ -324,15 +282,8 @@ public static Task RenderPartialAsync( string partialViewName, ViewDataDictionary viewData) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.RenderPartialAsync(partialViewName, htmlHelper.ViewData.Model, viewData); } @@ -354,15 +305,8 @@ public static Task RenderPartialAsync( string partialViewName, object model) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (partialViewName == null) - { - throw new ArgumentNullException(nameof(partialViewName)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(partialViewName); return htmlHelper.RenderPartialAsync(partialViewName, model, viewData: null); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperSelectExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperSelectExtensions.cs index a91c0fc11091..695fd1958e99 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperSelectExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperSelectExtensions.cs @@ -36,10 +36,7 @@ public static class HtmlHelperSelectExtensions /// public static IHtmlContent DropDownList(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DropDownList(expression, selectList: null, optionLabel: null, htmlAttributes: null); } @@ -76,10 +73,7 @@ public static IHtmlContent DropDownList( string expression, string optionLabel) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DropDownList( expression, @@ -117,10 +111,7 @@ public static IHtmlContent DropDownList( string expression, IEnumerable selectList) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DropDownList(expression, selectList, optionLabel: null, htmlAttributes: null); } @@ -159,10 +150,7 @@ public static IHtmlContent DropDownList( IEnumerable selectList, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DropDownList(expression, selectList, optionLabel: null, htmlAttributes: htmlAttributes); } @@ -200,10 +188,7 @@ public static IHtmlContent DropDownList( IEnumerable selectList, string optionLabel) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.DropDownList(expression, selectList, optionLabel, htmlAttributes: null); } @@ -237,15 +222,8 @@ public static IHtmlContent DropDownListFor( Expression> expression, IEnumerable selectList) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DropDownListFor(expression, selectList, optionLabel: null, htmlAttributes: null); } @@ -284,15 +262,8 @@ public static IHtmlContent DropDownListFor( IEnumerable selectList, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DropDownListFor( expression, @@ -334,15 +305,8 @@ public static IHtmlContent DropDownListFor( IEnumerable selectList, string optionLabel) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes: null); } @@ -372,10 +336,7 @@ public static IHtmlContent DropDownListFor( /// public static IHtmlContent ListBox(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ListBox(expression, selectList: null, htmlAttributes: null); } @@ -409,10 +370,7 @@ public static IHtmlContent ListBox( string expression, IEnumerable selectList) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ListBox(expression, selectList, htmlAttributes: null); } @@ -446,15 +404,8 @@ public static IHtmlContent ListBoxFor( Expression> expression, IEnumerable selectList) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ListBoxFor(expression, selectList, htmlAttributes: null); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValidationExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValidationExtensions.cs index ab0fc948b452..4a26e5173511 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValidationExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValidationExtensions.cs @@ -30,10 +30,7 @@ public static IHtmlContent ValidationMessage( this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationMessage(expression, message: null, htmlAttributes: null, tag: null); } @@ -59,10 +56,7 @@ public static IHtmlContent ValidationMessage( string expression, string message) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationMessage(expression, message, htmlAttributes: null, tag: null); } @@ -93,10 +87,7 @@ public static IHtmlContent ValidationMessage( string expression, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationMessage(expression, message: null, htmlAttributes: htmlAttributes, tag: null); } @@ -127,10 +118,7 @@ public static IHtmlContent ValidationMessage( string message, string tag) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationMessage(expression, message, htmlAttributes: null, tag: tag); } @@ -163,10 +151,7 @@ public static IHtmlContent ValidationMessage( string message, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationMessage(expression, message, htmlAttributes, tag: null); } @@ -192,15 +177,8 @@ public static IHtmlContent ValidationMessageFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ValidationMessageFor(expression, message: null, htmlAttributes: null, tag: null); } @@ -228,15 +206,8 @@ public static IHtmlContent ValidationMessageFor( Expression> expression, string message) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ValidationMessageFor(expression, message, htmlAttributes: null, tag: null); } @@ -271,15 +242,8 @@ public static IHtmlContent ValidationMessageFor( string message, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ValidationMessageFor(expression, message, htmlAttributes, tag: null); } @@ -312,15 +276,8 @@ public static IHtmlContent ValidationMessageFor( string message, string tag) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ValidationMessageFor(expression, message, htmlAttributes: null, tag: tag); } @@ -336,10 +293,7 @@ public static IHtmlContent ValidationMessageFor( /// public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors: false, @@ -362,10 +316,7 @@ public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper) /// public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper, bool excludePropertyErrors) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors, @@ -388,10 +339,7 @@ public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper, bool e /// public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper, string message) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors: false, @@ -417,10 +365,7 @@ public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper, string /// public static IHtmlContent ValidationSummary(this IHtmlHelper htmlHelper, string message, string tag) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors: false, @@ -449,10 +394,7 @@ public static IHtmlContent ValidationSummary( bool excludePropertyErrors, string message) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors, @@ -483,10 +425,7 @@ public static IHtmlContent ValidationSummary( string message, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors: false, @@ -521,10 +460,7 @@ public static IHtmlContent ValidationSummary( object htmlAttributes, string tag) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors: false, @@ -557,10 +493,7 @@ public static IHtmlContent ValidationSummary( string message, string tag) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary( excludePropertyErrors, @@ -595,10 +528,7 @@ public static IHtmlContent ValidationSummary( string message, object htmlAttributes) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes, tag: null); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValueExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValueExtensions.cs index aea90a352e2c..2cf884aaf3b0 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValueExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/HtmlHelperValueExtensions.cs @@ -26,10 +26,7 @@ public static class HtmlHelperValueExtensions /// public static string Value(this IHtmlHelper htmlHelper, string expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Value(expression, format: null); } @@ -53,15 +50,8 @@ public static string ValueFor( this IHtmlHelper htmlHelper, Expression> expression) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } - - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); + ArgumentNullException.ThrowIfNull(expression); return htmlHelper.ValueFor(expression, format: null); } @@ -81,10 +71,7 @@ public static string ValueFor( /// public static string ValueForModel(this IHtmlHelper htmlHelper) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Value(expression: null, format: null); } @@ -109,10 +96,7 @@ public static string ValueForModel(this IHtmlHelper htmlHelper) /// public static string ValueForModel(this IHtmlHelper htmlHelper, string format) { - if (htmlHelper == null) - { - throw new ArgumentNullException(nameof(htmlHelper)); - } + ArgumentNullException.ThrowIfNull(htmlHelper); return htmlHelper.Value(expression: null, format: format); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/MultiSelectList.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/MultiSelectList.cs index 8bd5f6ba8702..6f1fb4a38f4e 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/MultiSelectList.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/MultiSelectList.cs @@ -25,10 +25,7 @@ public class MultiSelectList : IEnumerable public MultiSelectList(IEnumerable items) : this(items, selectedValues: null) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -39,10 +36,7 @@ public MultiSelectList(IEnumerable items) public MultiSelectList(IEnumerable items, IEnumerable selectedValues) : this(items, dataValueField: null, dataTextField: null, selectedValues: selectedValues) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -54,10 +48,7 @@ public MultiSelectList(IEnumerable items, IEnumerable selectedValues) public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField) : this(items, dataValueField, dataTextField, selectedValues: null) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -74,10 +65,7 @@ public MultiSelectList( IEnumerable selectedValues) : this(items, dataValueField, dataTextField, selectedValues, dataGroupField: null) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -100,10 +88,7 @@ public MultiSelectList( IEnumerable selectedValues, string dataGroupField) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); Items = items; DataValueField = dataValueField; diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/MvcForm.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/MvcForm.cs index 99343b56569c..d454dcfe0fa2 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/MvcForm.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/MvcForm.cs @@ -24,15 +24,8 @@ public class MvcForm : IDisposable /// The . public MvcForm(ViewContext viewContext, HtmlEncoder htmlEncoder) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(htmlEncoder); _viewContext = viewContext; _htmlEncoder = htmlEncoder; diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/SelectList.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/SelectList.cs index a90890686546..c8242c8131b7 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/SelectList.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/SelectList.cs @@ -19,10 +19,7 @@ public class SelectList : MultiSelectList public SelectList(IEnumerable items) : this(items, selectedValue: null) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -33,10 +30,7 @@ public SelectList(IEnumerable items) public SelectList(IEnumerable items, object selectedValue) : this(items, dataValueField: null, dataTextField: null, selectedValue: selectedValue) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -48,10 +42,7 @@ public SelectList(IEnumerable items, object selectedValue) public SelectList(IEnumerable items, string dataValueField, string dataTextField) : this(items, dataValueField, dataTextField, selectedValue: null) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); } /// @@ -68,10 +59,7 @@ public SelectList( object selectedValue) : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue)) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); SelectedValue = selectedValue; } @@ -97,10 +85,7 @@ public SelectList( string dataGroupField) : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue), dataGroupField) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); SelectedValue = selectedValue; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs index 3e9a59aac840..86d371ff9a1d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/TagBuilder.cs @@ -149,10 +149,7 @@ public void AddCssClass(string value) /// public static string CreateSanitizedId(string? name, string invalidCharReplacement) { - if (invalidCharReplacement == null) - { - throw new ArgumentNullException(nameof(invalidCharReplacement)); - } + ArgumentNullException.ThrowIfNull(invalidCharReplacement); if (string.IsNullOrEmpty(name)) { @@ -223,10 +220,7 @@ public static string CreateSanitizedId(string? name, string invalidCharReplaceme /// public void GenerateId(string name, string invalidCharReplacement) { - if (invalidCharReplacement == null) - { - throw new ArgumentNullException(nameof(invalidCharReplacement)); - } + ArgumentNullException.ThrowIfNull(invalidCharReplacement); if (string.IsNullOrEmpty(name)) { @@ -337,15 +331,8 @@ public void MergeAttributes(IDictionary attributes, /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); WriteTo(this, writer, encoder, TagRenderMode); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewComponentHelperExtensions.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewComponentHelperExtensions.cs index 3a3b173a9d9f..f2547b9b5209 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewComponentHelperExtensions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewComponentHelperExtensions.cs @@ -21,10 +21,7 @@ public static class ViewComponentHelperExtensions /// public static Task InvokeAsync(this IViewComponentHelper helper, string name) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.InvokeAsync(name, arguments: null); } @@ -38,10 +35,7 @@ public static Task InvokeAsync(this IViewComponentHelper helper, s /// public static Task InvokeAsync(this IViewComponentHelper helper, Type componentType) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.InvokeAsync(componentType, arguments: null); } @@ -56,10 +50,7 @@ public static Task InvokeAsync(this IViewComponentHelper helper, T /// public static Task InvokeAsync(this IViewComponentHelper helper, object? arguments) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.InvokeAsync(typeof(TComponent), arguments); } @@ -73,10 +64,7 @@ public static Task InvokeAsync(this IViewComponentHelp /// public static Task InvokeAsync(this IViewComponentHelper helper) { - if (helper == null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); return helper.InvokeAsync(typeof(TComponent), arguments: null); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewContext.cs b/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewContext.cs index 48327508a413..81986d86d34c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewContext.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Rendering/ViewContext.cs @@ -51,35 +51,12 @@ public ViewContext( HtmlHelperOptions htmlHelperOptions) : base(actionContext) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (view == null) - { - throw new ArgumentNullException(nameof(view)); - } - - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } - - if (tempData == null) - { - throw new ArgumentNullException(nameof(tempData)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (htmlHelperOptions == null) - { - throw new ArgumentNullException(nameof(htmlHelperOptions)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(viewData); + ArgumentNullException.ThrowIfNull(tempData); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(htmlHelperOptions); View = view; ViewData = viewData; @@ -109,25 +86,10 @@ public ViewContext( TextWriter writer) : base(viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (view == null) - { - throw new ArgumentNullException(nameof(view)); - } - - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(view); + ArgumentNullException.ThrowIfNull(viewData); + ArgumentNullException.ThrowIfNull(writer); FormContext = viewContext.FormContext; @@ -157,10 +119,7 @@ public virtual FormContext FormContext set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _formContext = value; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/SessionStateTempDataProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/SessionStateTempDataProvider.cs index 99c201015cec..f0ef519d5bb4 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/SessionStateTempDataProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/SessionStateTempDataProvider.cs @@ -27,10 +27,7 @@ public SessionStateTempDataProvider(TempDataSerializer tempDataSerializer) /// public virtual IDictionary LoadTempData(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Accessing Session property will throw if the session middleware is not enabled. var session = context.Session; @@ -49,10 +46,7 @@ public virtual IDictionary LoadTempData(HttpContext context) /// public virtual void SaveTempData(HttpContext context, IDictionary values) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); // Accessing Session property will throw if the session middleware is not enabled. var session = context.Session; diff --git a/src/Mvc/Mvc.ViewFeatures/src/SkipStatusCodePagesAttribute.cs b/src/Mvc/Mvc.ViewFeatures/src/SkipStatusCodePagesAttribute.cs index 3a8951532597..c0abec8fa222 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/SkipStatusCodePagesAttribute.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/SkipStatusCodePagesAttribute.cs @@ -21,10 +21,7 @@ public void OnResourceExecuted(ResourceExecutedContext context) /// public void OnResourceExecuting(ResourceExecutingContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var statusCodeFeature = context.HttpContext.Features.Get(); if (statusCodeFeature != null) diff --git a/src/Mvc/Mvc.ViewFeatures/src/StringHtmlContent.cs b/src/Mvc/Mvc.ViewFeatures/src/StringHtmlContent.cs index 81afd193874f..014171239b7c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/StringHtmlContent.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/StringHtmlContent.cs @@ -29,15 +29,8 @@ public StringHtmlContent(string input) /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); encoder.Encode(writer, _input); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionary.cs b/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionary.cs index f29c43a6dca7..ecf7b16616a6 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionary.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionary.cs @@ -30,15 +30,8 @@ public class TempDataDictionary : ITempDataDictionary /// The used to Load and Save data. public TempDataDictionary(HttpContext context, ITempDataProvider provider) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(provider); _provider = provider; _loaded = false; diff --git a/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionaryFactory.cs b/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionaryFactory.cs index e98d864c2111..2e63bb407acf 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionaryFactory.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/TempDataDictionaryFactory.cs @@ -20,10 +20,7 @@ public class TempDataDictionaryFactory : ITempDataDictionaryFactory /// The . public TempDataDictionaryFactory(ITempDataProvider provider) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullException.ThrowIfNull(provider); _provider = provider; } @@ -31,10 +28,7 @@ public TempDataDictionaryFactory(ITempDataProvider provider) /// public ITempDataDictionary GetTempData(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); object obj; ITempDataDictionary result; diff --git a/src/Mvc/Mvc.ViewFeatures/src/TemplateBuilder.cs b/src/Mvc/Mvc.ViewFeatures/src/TemplateBuilder.cs index f0306adfda56..d1ddc84325ae 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/TemplateBuilder.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/TemplateBuilder.cs @@ -36,30 +36,11 @@ public TemplateBuilder( bool readOnly, object additionalViewData) { - if (viewEngine == null) - { - throw new ArgumentNullException(nameof(viewEngine)); - } - - if (bufferScope == null) - { - throw new ArgumentNullException(nameof(bufferScope)); - } - - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } - - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } + ArgumentNullException.ThrowIfNull(viewEngine); + ArgumentNullException.ThrowIfNull(bufferScope); + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(viewData); + ArgumentNullException.ThrowIfNull(modelExplorer); _viewEngine = viewEngine; _bufferScope = bufferScope; diff --git a/src/Mvc/Mvc.ViewFeatures/src/TemplateRenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/TemplateRenderer.cs index 89193735a2da..eae6181bf493 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/TemplateRenderer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/TemplateRenderer.cs @@ -83,25 +83,10 @@ public TemplateRenderer( string templateName, bool readOnly) { - if (viewEngine == null) - { - throw new ArgumentNullException(nameof(viewEngine)); - } - - if (bufferScope == null) - { - throw new ArgumentNullException(nameof(bufferScope)); - } - - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } + ArgumentNullException.ThrowIfNull(viewEngine); + ArgumentNullException.ThrowIfNull(bufferScope); + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(viewData); _viewEngine = viewEngine; _bufferScope = bufferScope; diff --git a/src/Mvc/Mvc.ViewFeatures/src/TryGetValueProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/TryGetValueProvider.cs index ecefee49dd36..95582ddc8bd8 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/TryGetValueProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/TryGetValueProvider.cs @@ -27,10 +27,7 @@ public static class TryGetValueProvider /// The . public static TryGetValueDelegate CreateInstance(Type targetType) { - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } + ArgumentNullException.ThrowIfNull(targetType); TryGetValueDelegate result; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ValidationHtmlAttributeProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/ValidationHtmlAttributeProvider.cs index 041add0fd067..b981a91dab78 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ValidationHtmlAttributeProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ValidationHtmlAttributeProvider.cs @@ -53,20 +53,9 @@ public virtual void AddAndTrackValidationAttributes( string expression, IDictionary attributes) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (modelExplorer == null) - { - throw new ArgumentNullException(nameof(modelExplorer)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(modelExplorer); + ArgumentNullException.ThrowIfNull(attributes); // Don't track fields when client-side validation is disabled. var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponent.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponent.cs index c80f049751d1..c9b01e64d266 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponent.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponent.cs @@ -93,10 +93,7 @@ public IUrlHelper Url } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _url = value; } @@ -120,10 +117,7 @@ public ViewComponentContext ViewComponentContext } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _viewComponentContext = value; } @@ -162,10 +156,7 @@ public ICompositeViewEngine ViewEngine } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _viewEngine = value; } @@ -178,10 +169,7 @@ public ICompositeViewEngine ViewEngine /// A . public ContentViewComponentResult Content(string content) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); return new ContentViewComponentResult(content); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResult.cs index 77c661b932e6..e22652b05fee 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResult.cs @@ -58,10 +58,7 @@ public class ViewComponentResult : ActionResult, IStatusCodeActionResult /// public override Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var services = context.HttpContext.RequestServices; var executor = services.GetService>(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs index d56b66ff3aff..50831a252327 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs @@ -49,30 +49,11 @@ public ViewComponentResultExecutor( ITempDataDictionaryFactory tempDataDictionaryFactory, IHttpResponseStreamWriterFactory writerFactory) { - if (mvcHelperOptions == null) - { - throw new ArgumentNullException(nameof(mvcHelperOptions)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (modelMetadataProvider == null) - { - throw new ArgumentNullException(nameof(modelMetadataProvider)); - } - - if (tempDataDictionaryFactory == null) - { - throw new ArgumentNullException(nameof(tempDataDictionaryFactory)); - } + ArgumentNullException.ThrowIfNull(mvcHelperOptions); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(modelMetadataProvider); + ArgumentNullException.ThrowIfNull(tempDataDictionaryFactory); _htmlHelperOptions = mvcHelperOptions.Value.HtmlHelperOptions; _logger = loggerFactory.CreateLogger(); @@ -85,15 +66,8 @@ public ViewComponentResultExecutor( /// public virtual async Task ExecuteAsync(ActionContext context, ViewComponentResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var response = context.HttpContext.Response; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ContentViewComponentResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ContentViewComponentResult.cs index 7ad2487df691..d3c1b0f87881 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ContentViewComponentResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ContentViewComponentResult.cs @@ -20,10 +20,7 @@ public class ContentViewComponentResult : IViewComponentResult /// Content to write. The content will be HTML encoded when written. public ContentViewComponentResult(string content) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } + ArgumentNullException.ThrowIfNull(content); Content = content; } @@ -39,10 +36,7 @@ public ContentViewComponentResult(string content) /// The . public void Execute(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); context.HtmlEncoder.Encode(context.Writer, Content); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentActivator.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentActivator.cs index b6c5e4da6365..9595d36686c1 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentActivator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentActivator.cs @@ -26,10 +26,7 @@ internal sealed class DefaultViewComponentActivator : IViewComponentActivator /// public DefaultViewComponentActivator(ITypeActivatorCache typeActivatorCache) { - if (typeActivatorCache == null) - { - throw new ArgumentNullException(nameof(typeActivatorCache)); - } + ArgumentNullException.ThrowIfNull(typeActivatorCache); _typeActivatorCache = typeActivatorCache; } @@ -37,10 +34,7 @@ public DefaultViewComponentActivator(ITypeActivatorCache typeActivatorCache) /// public object Create(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var componentType = context.ViewComponentDescriptor.TypeInfo; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentDescriptorProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentDescriptorProvider.cs index be321077bdbd..55d1bf40d82f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentDescriptorProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentDescriptorProvider.cs @@ -23,10 +23,7 @@ public class DefaultViewComponentDescriptorProvider : IViewComponentDescriptorPr /// The . public DefaultViewComponentDescriptorProvider(ApplicationPartManager partManager) { - if (partManager == null) - { - throw new ArgumentNullException(nameof(partManager)); - } + ArgumentNullException.ThrowIfNull(partManager); _partManager = partManager; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentFactory.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentFactory.cs index c03306ce9676..a03c04c40e22 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentFactory.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentFactory.cs @@ -24,10 +24,7 @@ public class DefaultViewComponentFactory : IViewComponentFactory /// public DefaultViewComponentFactory(IViewComponentActivator activator) { - if (activator == null) - { - throw new ArgumentNullException(nameof(activator)); - } + ArgumentNullException.ThrowIfNull(activator); _activator = activator; @@ -42,10 +39,7 @@ public DefaultViewComponentFactory(IViewComponentActivator activator) /// public object CreateViewComponent(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var component = _activator.Create(context); @@ -75,15 +69,8 @@ private static PropertyActivator CreateActivateInfo(Proper /// public void ReleaseViewComponent(ViewComponentContext context, object component) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(component); _activator.Release(context, component); } @@ -91,15 +78,8 @@ public void ReleaseViewComponent(ViewComponentContext context, object component) /// public ValueTask ReleaseViewComponentAsync(ViewComponentContext context, object component) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(component); return _activator.ReleaseAsync(context, component); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentHelper.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentHelper.cs index b591208800ac..8492e16b97a7 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentHelper.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentHelper.cs @@ -42,30 +42,11 @@ public DefaultViewComponentHelper( IViewComponentInvokerFactory invokerFactory, IViewBufferScope viewBufferScope) { - if (descriptorProvider == null) - { - throw new ArgumentNullException(nameof(descriptorProvider)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (selector == null) - { - throw new ArgumentNullException(nameof(selector)); - } - - if (invokerFactory == null) - { - throw new ArgumentNullException(nameof(invokerFactory)); - } - - if (viewBufferScope == null) - { - throw new ArgumentNullException(nameof(viewBufferScope)); - } + ArgumentNullException.ThrowIfNull(descriptorProvider); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(selector); + ArgumentNullException.ThrowIfNull(invokerFactory); + ArgumentNullException.ThrowIfNull(viewBufferScope); _descriptorProvider = descriptorProvider; _htmlEncoder = htmlEncoder; @@ -77,10 +58,7 @@ public DefaultViewComponentHelper( /// public void Contextualize(ViewContext viewContext) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); _viewContext = viewContext; } @@ -88,10 +66,7 @@ public void Contextualize(ViewContext viewContext) /// public Task InvokeAsync(string name, object? arguments) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var descriptor = _selector.SelectComponent(name); if (descriptor == null) @@ -109,10 +84,7 @@ public Task InvokeAsync(string name, object? arguments) /// public Task InvokeAsync(Type componentType, object? arguments) { - if (componentType == null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(componentType); var descriptor = SelectComponent(componentType); return InvokeCoreAsync(descriptor, arguments); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs index 10279954b49c..001f42c3f752 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs @@ -36,25 +36,10 @@ public DefaultViewComponentInvoker( DiagnosticListener diagnosticListener, ILogger logger) { - if (viewComponentFactory == null) - { - throw new ArgumentNullException(nameof(viewComponentFactory)); - } - - if (viewComponentInvokerCache == null) - { - throw new ArgumentNullException(nameof(viewComponentInvokerCache)); - } - - if (diagnosticListener == null) - { - throw new ArgumentNullException(nameof(diagnosticListener)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(viewComponentFactory); + ArgumentNullException.ThrowIfNull(viewComponentInvokerCache); + ArgumentNullException.ThrowIfNull(diagnosticListener); + ArgumentNullException.ThrowIfNull(logger); _viewComponentFactory = viewComponentFactory; _viewComponentInvokerCache = viewComponentInvokerCache; @@ -65,10 +50,7 @@ public DefaultViewComponentInvoker( /// public async Task InvokeAsync(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = _viewComponentInvokerCache.GetViewComponentMethodExecutor(context); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvokerFactory.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvokerFactory.cs index 062a9e40ab67..3376fb7587f8 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvokerFactory.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvokerFactory.cs @@ -19,25 +19,10 @@ public DefaultViewComponentInvokerFactory( DiagnosticListener diagnosticListener, ILoggerFactory loggerFactory) { - if (viewComponentFactory == null) - { - throw new ArgumentNullException(nameof(viewComponentFactory)); - } - - if (viewComponentInvokerCache == null) - { - throw new ArgumentNullException(nameof(viewComponentInvokerCache)); - } - - if (diagnosticListener == null) - { - throw new ArgumentNullException(nameof(diagnosticListener)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(viewComponentFactory); + ArgumentNullException.ThrowIfNull(viewComponentInvokerCache); + ArgumentNullException.ThrowIfNull(diagnosticListener); + ArgumentNullException.ThrowIfNull(loggerFactory); _viewComponentFactory = viewComponentFactory; _diagnosticListener = diagnosticListener; @@ -52,10 +37,7 @@ public DefaultViewComponentInvokerFactory( // considering that possibility. public IViewComponentInvoker CreateInstance(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); return new DefaultViewComponentInvoker( _viewComponentFactory, diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentSelector.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentSelector.cs index 6d3892a59e25..c58087a4273d 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentSelector.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentSelector.cs @@ -27,10 +27,7 @@ public DefaultViewComponentSelector(IViewComponentDescriptorCollectionProvider d /// public ViewComponentDescriptor SelectComponent(string componentName) { - if (componentName == null) - { - throw new ArgumentNullException(nameof(componentName)); - } + ArgumentNullException.ThrowIfNull(componentName); var collection = _descriptorProvider.ViewComponents; if (_cache == null || _cache.Version != collection.Version) diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/HtmlContentViewComponentResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/HtmlContentViewComponentResult.cs index 5b56f90ff963..c1ff73766d61 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/HtmlContentViewComponentResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/HtmlContentViewComponentResult.cs @@ -21,10 +21,7 @@ public class HtmlContentViewComponentResult : IViewComponentResult /// public HtmlContentViewComponentResult(IHtmlContent encodedContent) { - if (encodedContent == null) - { - throw new ArgumentNullException(nameof(encodedContent)); - } + ArgumentNullException.ThrowIfNull(encodedContent); EncodedContent = encodedContent; } @@ -40,10 +37,7 @@ public HtmlContentViewComponentResult(IHtmlContent encodedContent) /// The . public void Execute(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); context.Writer.Write(EncodedContent); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ServiceBasedViewComponentActivator.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ServiceBasedViewComponentActivator.cs index 387a5c96ab5d..5d422e28b909 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ServiceBasedViewComponentActivator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ServiceBasedViewComponentActivator.cs @@ -14,10 +14,7 @@ public class ServiceBasedViewComponentActivator : IViewComponentActivator /// public object Create(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var viewComponentType = context.ViewComponentDescriptor.TypeInfo.AsType(); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentContext.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentContext.cs index 5a503d937336..b8c0c82475a1 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentContext.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentContext.cs @@ -43,30 +43,11 @@ public ViewComponentContext( ViewContext viewContext, TextWriter writer) { - if (viewComponentDescriptor == null) - { - throw new ArgumentNullException(nameof(viewComponentDescriptor)); - } - - if (arguments == null) - { - throw new ArgumentNullException(nameof(arguments)); - } - - if (htmlEncoder == null) - { - throw new ArgumentNullException(nameof(htmlEncoder)); - } - - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } - - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(viewComponentDescriptor); + ArgumentNullException.ThrowIfNull(arguments); + ArgumentNullException.ThrowIfNull(htmlEncoder); + ArgumentNullException.ThrowIfNull(viewContext); + ArgumentNullException.ThrowIfNull(writer); ViewComponentDescriptor = viewComponentDescriptor; Arguments = arguments; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentConventions.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentConventions.cs index 52f666039fd9..09440c8e86ec 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentConventions.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentConventions.cs @@ -22,10 +22,7 @@ public static class ViewComponentConventions /// public static string GetComponentName(TypeInfo componentType) { - if (componentType == null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(componentType); var attribute = componentType.GetCustomAttribute(); if (attribute != null && !string.IsNullOrEmpty(attribute.Name)) @@ -52,10 +49,7 @@ public static string GetComponentName(TypeInfo componentType) /// The full name of the component. public static string GetComponentFullName(TypeInfo componentType) { - if (componentType == null) - { - throw new ArgumentNullException(nameof(componentType)); - } + ArgumentNullException.ThrowIfNull(componentType); var attribute = componentType.GetCustomAttribute(); if (!string.IsNullOrEmpty(attribute?.Name)) @@ -97,10 +91,7 @@ private static string GetShortNameByConvention(TypeInfo componentType) /// If the type is a component. public static bool IsComponent(TypeInfo typeInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); if (!typeInfo.IsClass || !typeInfo.IsPublic || diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptor.cs index e27af5bb6741..917744a1315f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptor.cs @@ -39,10 +39,7 @@ public string DisplayName set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _displayName = value; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptorCollection.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptorCollection.cs index 8abebc01de0d..d888399d082f 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptorCollection.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentDescriptorCollection.cs @@ -15,10 +15,7 @@ public class ViewComponentDescriptorCollection /// The unique version of discovered view components. public ViewComponentDescriptorCollection(IEnumerable items, int version) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); Items = new List(items); Version = version; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentFeatureProvider.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentFeatureProvider.cs index abe4d5647f74..56fc834317c8 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentFeatureProvider.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewComponentFeatureProvider.cs @@ -14,15 +14,8 @@ public class ViewComponentFeatureProvider : IApplicationFeatureProvider public void PopulateFeature(IEnumerable parts, ViewComponentFeature feature) { - if (parts == null) - { - throw new ArgumentNullException(nameof(parts)); - } - - if (feature == null) - { - throw new ArgumentNullException(nameof(feature)); - } + ArgumentNullException.ThrowIfNull(parts); + ArgumentNullException.ThrowIfNull(feature); foreach (var type in parts.OfType().SelectMany(p => p.Types)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewViewComponentResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewViewComponentResult.cs index 57c66c7a77ea..bb23b9edb5eb 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewViewComponentResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/ViewViewComponentResult.cs @@ -53,10 +53,7 @@ public class ViewViewComponentResult : IViewComponentResult /// public void Execute(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var task = ExecuteAsync(context); task.GetAwaiter().GetResult(); @@ -70,10 +67,7 @@ public void Execute(ViewComponentContext context) /// A which will complete when view rendering is completed. public async Task ExecuteAsync(ViewComponentContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var viewEngine = ViewEngine ?? ResolveViewEngine(context); var viewContext = context.ViewContext; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs index 054575b0f47c..9521954b18d4 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionary.cs @@ -115,20 +115,9 @@ protected ViewDataDictionary( data: new Dictionary(StringComparer.OrdinalIgnoreCase), templateInfo: new TemplateInfo()) { - if (metadataProvider == null) - { - throw new ArgumentNullException(nameof(metadataProvider)); - } - - if (modelState == null) - { - throw new ArgumentNullException(nameof(modelState)); - } - - if (declaredModelType == null) - { - throw new ArgumentNullException(nameof(declaredModelType)); - } + ArgumentNullException.ThrowIfNull(metadataProvider); + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(declaredModelType); // Base ModelMetadata on the declared type. ModelExplorer = _metadataProvider.GetModelExplorerForType(declaredModelType, model: null); @@ -188,10 +177,7 @@ protected ViewDataDictionary(ViewDataDictionary source, object? model, Type decl data: new CopyOnWriteDictionary(source, StringComparer.OrdinalIgnoreCase), templateInfo: new TemplateInfo(source.TemplateInfo)) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); // A non-null Model must always be assignable to both _declaredModelType and ModelMetadata.ModelType. // @@ -531,10 +517,7 @@ private bool IsCompatibleWithDeclaredType(object? value) /// public void Add(string key, object? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); _data.Add(key, value); } @@ -542,10 +525,7 @@ public void Add(string key, object? value) /// public bool ContainsKey(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _data.ContainsKey(key); } @@ -553,10 +533,7 @@ public bool ContainsKey(string key) /// public bool Remove(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _data.Remove(key); } @@ -564,10 +541,7 @@ public bool Remove(string key) /// public bool TryGetValue(string key, out object? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); return _data.TryGetValue(key, out value); } @@ -593,10 +567,7 @@ public bool Contains(KeyValuePair item) /// public void CopyTo(KeyValuePair[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); _data.CopyTo(array, arrayIndex); } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionaryFactory.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionaryFactory.cs index 461caa991787..40362cc292c9 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionaryFactory.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewDataDictionaryFactory.cs @@ -11,10 +11,7 @@ internal static class ViewDataDictionaryFactory { public static Func CreateFactory(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var type = typeof(ViewDataDictionary<>).MakeGenericType(modelType); var constructor = type.GetConstructor(new[] { typeof(IModelMetadataProvider), typeof(ModelStateDictionary) }); @@ -35,10 +32,7 @@ public static Func CreateNestedFactory(Type modelType) { - if (modelType == null) - { - throw new ArgumentNullException(nameof(modelType)); - } + ArgumentNullException.ThrowIfNull(modelType); var type = typeof(ViewDataDictionary<>).MakeGenericType(modelType); var constructor = type.GetConstructor(new[] { typeof(ViewDataDictionary) }); diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs index a51b4361ddf2..778023689045 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewDataEvaluator.cs @@ -24,10 +24,7 @@ public static class ViewDataEvaluator /// public static ViewDataInfo Eval(ViewDataDictionary viewData, string expression) { - if (viewData == null) - { - throw new ArgumentNullException(nameof(viewData)); - } + ArgumentNullException.ThrowIfNull(viewData); // While it is not valid to generate a field for the top-level model itself because the result is an // unnamed input element, do not throw here if full name is null or empty. Support is needed for cases diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/CompositeViewEngine.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/CompositeViewEngine.cs index 0d2418d6d75d..627dd92b3b0a 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/CompositeViewEngine.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/CompositeViewEngine.cs @@ -27,10 +27,7 @@ public CompositeViewEngine(IOptions optionsAccessor) /// public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (string.IsNullOrEmpty(viewName)) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/ViewEngineResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/ViewEngineResult.cs index ad6d8091e255..e6ce7288b267 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/ViewEngineResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewEngines/ViewEngineResult.cs @@ -50,15 +50,8 @@ public static ViewEngineResult NotFound( string viewName, IEnumerable searchedLocations) { - if (viewName == null) - { - throw new ArgumentNullException(nameof(viewName)); - } - - if (searchedLocations == null) - { - throw new ArgumentNullException(nameof(searchedLocations)); - } + ArgumentNullException.ThrowIfNull(viewName); + ArgumentNullException.ThrowIfNull(searchedLocations); return new ViewEngineResult(viewName) { @@ -74,15 +67,8 @@ public static ViewEngineResult NotFound( /// The found result. public static ViewEngineResult Found(string viewName, IView view) { - if (viewName == null) - { - throw new ArgumentNullException(nameof(viewName)); - } - - if (view == null) - { - throw new ArgumentNullException(nameof(view)); - } + ArgumentNullException.ThrowIfNull(viewName); + ArgumentNullException.ThrowIfNull(view); return new ViewEngineResult(viewName) { diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs index 9eeecd8abee4..43fee76e0f48 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs @@ -44,20 +44,9 @@ public ViewExecutor( IModelMetadataProvider modelMetadataProvider) : this(writerFactory, viewEngine, diagnosticListener) { - if (viewOptions == null) - { - throw new ArgumentNullException(nameof(viewOptions)); - } - - if (tempDataFactory == null) - { - throw new ArgumentNullException(nameof(tempDataFactory)); - } - - if (diagnosticListener == null) - { - throw new ArgumentNullException(nameof(diagnosticListener)); - } + ArgumentNullException.ThrowIfNull(viewOptions); + ArgumentNullException.ThrowIfNull(tempDataFactory); + ArgumentNullException.ThrowIfNull(diagnosticListener); ViewOptions = viewOptions.Value; TempDataFactory = tempDataFactory; @@ -75,20 +64,9 @@ protected ViewExecutor( ICompositeViewEngine viewEngine, DiagnosticListener diagnosticListener) { - if (writerFactory == null) - { - throw new ArgumentNullException(nameof(writerFactory)); - } - - if (viewEngine == null) - { - throw new ArgumentNullException(nameof(viewEngine)); - } - - if (diagnosticListener == null) - { - throw new ArgumentNullException(nameof(diagnosticListener)); - } + ArgumentNullException.ThrowIfNull(writerFactory); + ArgumentNullException.ThrowIfNull(viewEngine); + ArgumentNullException.ThrowIfNull(diagnosticListener); WriterFactory = writerFactory; ViewEngine = viewEngine; @@ -148,15 +126,8 @@ public virtual async Task ExecuteAsync( string? contentType, int? statusCode) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (view == null) - { - throw new ArgumentNullException(nameof(view)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(view); if (ViewOptions == null) { @@ -211,10 +182,7 @@ protected async Task ExecuteAsync( string? contentType, int? statusCode) { - if (viewContext == null) - { - throw new ArgumentNullException(nameof(viewContext)); - } + ArgumentNullException.ThrowIfNull(viewContext); var response = viewContext.HttpContext.Response; diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewResult.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewResult.cs index 4176ed9b14d3..b7e46adcc908 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewResult.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewResult.cs @@ -59,10 +59,7 @@ public class ViewResult : ActionResult, IStatusCodeActionResult /// public override async Task ExecuteResultAsync(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var executor = context.HttpContext.RequestServices.GetService>(); if (executor == null) diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewResultExecutor.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewResultExecutor.cs index bde2700da584..3c4628c54351 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewResultExecutor.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewResultExecutor.cs @@ -42,10 +42,7 @@ public ViewResultExecutor( IModelMetadataProvider modelMetadataProvider) : base(viewOptions, writerFactory, viewEngine, tempDataFactory, diagnosticListener, modelMetadataProvider) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); Logger = loggerFactory.CreateLogger(); } @@ -63,15 +60,8 @@ public ViewResultExecutor( /// A . public virtual ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult) { - if (actionContext == null) - { - throw new ArgumentNullException(nameof(actionContext)); - } - - if (viewResult == null) - { - throw new ArgumentNullException(nameof(viewResult)); - } + ArgumentNullException.ThrowIfNull(actionContext); + ArgumentNullException.ThrowIfNull(viewResult); var viewEngine = viewResult.ViewEngine ?? ViewEngine; @@ -148,15 +138,8 @@ private void OutputDiagnostics(ActionContext actionContext, ViewResult viewResul /// public async Task ExecuteAsync(ActionContext context, ViewResult result) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(result); var stopwatch = ValueStopwatch.StartNew(); @@ -180,10 +163,7 @@ await ExecuteAsync( private static string? GetActionName(ActionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (!context.RouteData.Values.TryGetValue(ActionNameKey, out var routeValue)) { diff --git a/src/Mvc/Mvc/src/MvcServiceCollectionExtensions.cs b/src/Mvc/Mvc/src/MvcServiceCollectionExtensions.cs index 243228b4cbfd..cee62754969e 100644 --- a/src/Mvc/Mvc/src/MvcServiceCollectionExtensions.cs +++ b/src/Mvc/Mvc/src/MvcServiceCollectionExtensions.cs @@ -28,10 +28,7 @@ public static class MvcServiceCollectionExtensions /// An that can be used to further configure the MVC services. public static IMvcBuilder AddMvc(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddControllersWithViews(); return services.AddRazorPages(); @@ -45,15 +42,8 @@ public static IMvcBuilder AddMvc(this IServiceCollection services) /// An that can be used to further configure the MVC services. public static IMvcBuilder AddMvc(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(setupAction); var builder = services.AddMvc(); builder.Services.Configure(setupAction); @@ -88,10 +78,7 @@ public static IMvcBuilder AddMvc(this IServiceCollection services, Action public static IMvcBuilder AddControllers(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var builder = AddControllersCore(services); return new MvcBuilder(builder.Services, builder.PartManager); @@ -125,10 +112,7 @@ public static IMvcBuilder AddControllers(this IServiceCollection services) /// public static IMvcBuilder AddControllers(this IServiceCollection services, Action? configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); // This method excludes all of the view-related services by default. var builder = AddControllersCore(services); @@ -185,10 +169,7 @@ private static IMvcCoreBuilder AddControllersCore(IServiceCollection services) /// public static IMvcBuilder AddControllersWithViews(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var builder = AddControllersWithViewsCore(services); return new MvcBuilder(builder.Services, builder.PartManager); @@ -220,10 +201,7 @@ public static IMvcBuilder AddControllersWithViews(this IServiceCollection servic /// public static IMvcBuilder AddControllersWithViews(this IServiceCollection services, Action? configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); // This method excludes all of the view-related services by default. var builder = AddControllersWithViewsCore(services); @@ -270,10 +248,7 @@ private static IMvcCoreBuilder AddControllersWithViewsCore(IServiceCollection se /// public static IMvcBuilder AddRazorPages(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var builder = AddRazorPagesCore(services); return new MvcBuilder(builder.Services, builder.PartManager); @@ -303,10 +278,7 @@ public static IMvcBuilder AddRazorPages(this IServiceCollection services) /// public static IMvcBuilder AddRazorPages(this IServiceCollection services, Action? configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var builder = AddRazorPagesCore(services); if (configure != null) diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/SimpleValueProviderFactory.cs b/src/Mvc/shared/Mvc.Core.TestCommon/SimpleValueProviderFactory.cs index 9eb481fc1743..64681c973c8c 100644 --- a/src/Mvc/shared/Mvc.Core.TestCommon/SimpleValueProviderFactory.cs +++ b/src/Mvc/shared/Mvc.Core.TestCommon/SimpleValueProviderFactory.cs @@ -14,10 +14,7 @@ public SimpleValueProviderFactory() public SimpleValueProviderFactory(IValueProvider valueProvider) { - if (valueProvider == null) - { - throw new ArgumentNullException(nameof(valueProvider)); - } + ArgumentNullException.ThrowIfNull(valueProvider); _valueProvider = valueProvider; } diff --git a/src/Mvc/test/Mvc.FunctionalTests/Infrastructure/MvcWebApplicationBuilderExtensions.cs b/src/Mvc/test/Mvc.FunctionalTests/Infrastructure/MvcWebApplicationBuilderExtensions.cs index 407dce4161d7..a697f36f7c2c 100644 --- a/src/Mvc/test/Mvc.FunctionalTests/Infrastructure/MvcWebApplicationBuilderExtensions.cs +++ b/src/Mvc/test/Mvc.FunctionalTests/Infrastructure/MvcWebApplicationBuilderExtensions.cs @@ -21,15 +21,8 @@ public static class MvcWebApplicationBuilderExtensions public static IWebHostBuilder UseRequestCulture(this IWebHostBuilder builder, string culture, string uiCulture) where TStartup : class { - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } - - if (uiCulture == null) - { - throw new ArgumentNullException(nameof(uiCulture)); - } + ArgumentNullException.ThrowIfNull(culture); + ArgumentNullException.ThrowIfNull(uiCulture); builder.ConfigureServices(services => { diff --git a/src/Mvc/test/Mvc.IntegrationTests/BinderTypeBasedModelBinderIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/BinderTypeBasedModelBinderIntegrationTest.cs index 031cdfb10a44..d079d50959f8 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/BinderTypeBasedModelBinderIntegrationTest.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/BinderTypeBasedModelBinderIntegrationTest.cs @@ -317,10 +317,7 @@ private class AddressModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); @@ -345,10 +342,7 @@ private class Address3ModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); @@ -373,10 +367,7 @@ private class SuccessModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); var model = "Success"; @@ -394,10 +385,7 @@ private class NullModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); bindingContext.Result = ModelBindingResult.Success(model: null); @@ -409,10 +397,7 @@ private class NullModelNotSetModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); bindingContext.Result = ModelBindingResult.Failed(); diff --git a/src/Mvc/test/Mvc.IntegrationTests/ExcludeBindingMetadataProviderIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/ExcludeBindingMetadataProviderIntegrationTest.cs index bb4b34aa7921..3a6d4f05cb90 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/ExcludeBindingMetadataProviderIntegrationTest.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/ExcludeBindingMetadataProviderIntegrationTest.cs @@ -130,10 +130,7 @@ public class TypeModelBinderProvider : IModelBinderProvider /// public IModelBinder GetBinder(ModelBinderProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.Metadata.ModelType == typeof(Type)) { diff --git a/src/Mvc/test/Mvc.IntegrationTests/GenericModelBinderIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/GenericModelBinderIntegrationTest.cs index 7ec71743c5c4..62eade8503d5 100644 --- a/src/Mvc/test/Mvc.IntegrationTests/GenericModelBinderIntegrationTest.cs +++ b/src/Mvc/test/Mvc.IntegrationTests/GenericModelBinderIntegrationTest.cs @@ -165,10 +165,7 @@ private class AddressBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { - if (bindingContext == null) - { - throw new ArgumentNullException(nameof(bindingContext)); - } + ArgumentNullException.ThrowIfNull(bindingContext); Debug.Assert(bindingContext.Result == ModelBindingResult.Failed()); diff --git a/src/Mvc/test/WebSites/HtmlGenerationWebSite/Models/ProductRecommendations.cs b/src/Mvc/test/WebSites/HtmlGenerationWebSite/Models/ProductRecommendations.cs index d4603355731b..98e6902f0344 100644 --- a/src/Mvc/test/WebSites/HtmlGenerationWebSite/Models/ProductRecommendations.cs +++ b/src/Mvc/test/WebSites/HtmlGenerationWebSite/Models/ProductRecommendations.cs @@ -7,10 +7,7 @@ public class ProductRecommendations { public ProductRecommendations(params Product[] products) { - if (products == null) - { - throw new ArgumentNullException(nameof(products)); - } + ArgumentNullException.ThrowIfNull(products); Products = products; } diff --git a/src/Mvc/test/WebSites/HtmlGenerationWebSite/TestCacheTagHelper.cs b/src/Mvc/test/WebSites/HtmlGenerationWebSite/TestCacheTagHelper.cs index 36219ac43b9b..9f86959705c8 100644 --- a/src/Mvc/test/WebSites/HtmlGenerationWebSite/TestCacheTagHelper.cs +++ b/src/Mvc/test/WebSites/HtmlGenerationWebSite/TestCacheTagHelper.cs @@ -18,10 +18,7 @@ public TestCacheTagHelper( HtmlEncoder htmlEncoder, ILoggerFactory loggerFactory) : base(factory, htmlEncoder) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } diff --git a/src/Mvc/test/WebSites/RoutingWebSite/ControllerRouteTokenTransformerConvention.cs b/src/Mvc/test/WebSites/RoutingWebSite/ControllerRouteTokenTransformerConvention.cs index a71aa0b60be6..ad2c78e2d6b1 100644 --- a/src/Mvc/test/WebSites/RoutingWebSite/ControllerRouteTokenTransformerConvention.cs +++ b/src/Mvc/test/WebSites/RoutingWebSite/ControllerRouteTokenTransformerConvention.cs @@ -12,10 +12,7 @@ public class ControllerRouteTokenTransformerConvention : RouteTokenTransformerCo public ControllerRouteTokenTransformerConvention(Type controllerType, IOutboundParameterTransformer parameterTransformer) : base(parameterTransformer) { - if (parameterTransformer == null) - { - throw new ArgumentNullException(nameof(parameterTransformer)); - } + ArgumentNullException.ThrowIfNull(parameterTransformer); _controllerType = controllerType; } diff --git a/src/ObjectPool/src/DefaultObjectPoolProvider.cs b/src/ObjectPool/src/DefaultObjectPoolProvider.cs index 3526b522c00f..c735053f35e7 100644 --- a/src/ObjectPool/src/DefaultObjectPoolProvider.cs +++ b/src/ObjectPool/src/DefaultObjectPoolProvider.cs @@ -1,7 +1,8 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.ObjectPool; @@ -18,10 +19,7 @@ public class DefaultObjectPoolProvider : ObjectPoolProvider /// public override ObjectPool Create(IPooledObjectPolicy policy) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullThrowHelper.ThrowIfNull(policy); if (typeof(IDisposable).IsAssignableFrom(typeof(T))) { diff --git a/src/ObjectPool/src/LeakTrackingObjectPool.cs b/src/ObjectPool/src/LeakTrackingObjectPool.cs index f3b478e781e7..a411f39236e1 100644 --- a/src/ObjectPool/src/LeakTrackingObjectPool.cs +++ b/src/ObjectPool/src/LeakTrackingObjectPool.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; using System.Runtime.CompilerServices; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.ObjectPool; @@ -29,10 +30,7 @@ public class LeakTrackingObjectPool : ObjectPool where T : class /// The instance to track leaks in. public LeakTrackingObjectPool(ObjectPool inner) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullThrowHelper.ThrowIfNull(inner); _inner = inner; } diff --git a/src/ObjectPool/src/LeakTrackingObjectPoolProvider.cs b/src/ObjectPool/src/LeakTrackingObjectPoolProvider.cs index 9482dbbadc9f..b990e72625ff 100644 --- a/src/ObjectPool/src/LeakTrackingObjectPoolProvider.cs +++ b/src/ObjectPool/src/LeakTrackingObjectPoolProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.ObjectPool; @@ -21,10 +22,7 @@ public class LeakTrackingObjectPoolProvider : ObjectPoolProvider /// The to wrap. public LeakTrackingObjectPoolProvider(ObjectPoolProvider inner) { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } + ArgumentNullThrowHelper.ThrowIfNull(inner); _inner = inner; } diff --git a/src/ObjectPool/src/Microsoft.Extensions.ObjectPool.csproj b/src/ObjectPool/src/Microsoft.Extensions.ObjectPool.csproj index d0d451809969..4fb0813d6c1e 100644 --- a/src/ObjectPool/src/Microsoft.Extensions.ObjectPool.csproj +++ b/src/ObjectPool/src/Microsoft.Extensions.ObjectPool.csproj @@ -13,4 +13,9 @@ + + + + + diff --git a/src/Razor/Razor.Runtime/src/Hosting/DefaultRazorCompiledItem.cs b/src/Razor/Razor.Runtime/src/Hosting/DefaultRazorCompiledItem.cs index 91461146a6d4..e4bf95725801 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/DefaultRazorCompiledItem.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/DefaultRazorCompiledItem.cs @@ -9,20 +9,9 @@ internal sealed class DefaultRazorCompiledItem : RazorCompiledItem public DefaultRazorCompiledItem(Type type, string kind, string identifier) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (kind == null) - { - throw new ArgumentNullException(nameof(kind)); - } - - if (identifier == null) - { - throw new ArgumentNullException(nameof(identifier)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(kind); + ArgumentNullException.ThrowIfNull(identifier); Type = type; Kind = kind; diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemAttribute.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemAttribute.cs index 59f9cd8fa070..fa83111c7242 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemAttribute.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemAttribute.cs @@ -22,15 +22,8 @@ public sealed class RazorCompiledItemAttribute : Attribute /// public RazorCompiledItemAttribute(Type type, string kind, string identifier) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (kind == null) - { - throw new ArgumentNullException(nameof(kind)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(kind); Type = type; Kind = kind; diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemExtensions.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemExtensions.cs index ffee6ba396e7..c7308cf3a699 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemExtensions.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemExtensions.cs @@ -17,10 +17,7 @@ public static class RazorCompiledItemExtensions /// A list of . public static IReadOnlyList GetChecksumMetadata(this RazorCompiledItem item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); return item.Metadata.OfType().ToArray(); } diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemLoader.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemLoader.cs index 8c878335c201..0b8acf6ca617 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemLoader.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorCompiledItemLoader.cs @@ -33,10 +33,7 @@ public class RazorCompiledItemLoader /// A list of objects. public virtual IReadOnlyList LoadItems(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); var items = new List(); foreach (var attribute in LoadAttributes(assembly)) @@ -54,10 +51,7 @@ public virtual IReadOnlyList LoadItems(Assembly assembly) /// A created from . protected virtual RazorCompiledItem CreateItem(RazorCompiledItemAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); return new DefaultRazorCompiledItem(attribute.Type, attribute.Kind, attribute.Identifier); } @@ -70,10 +64,7 @@ protected virtual RazorCompiledItem CreateItem(RazorCompiledItemAttribute attrib /// A list of attributes. protected IEnumerable LoadAttributes(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullException.ThrowIfNull(assembly); return assembly.GetCustomAttributes(); } diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorConfigurationNameAttribute.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorConfigurationNameAttribute.cs index 044813376ecb..f4261ba11fed 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorConfigurationNameAttribute.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorConfigurationNameAttribute.cs @@ -20,10 +20,7 @@ public sealed class RazorConfigurationNameAttribute : Attribute /// The name of the Razor configuration. public RazorConfigurationNameAttribute(string configurationName) { - if (configurationName == null) - { - throw new ArgumentNullException(nameof(configurationName)); - } + ArgumentNullException.ThrowIfNull(configurationName); ConfigurationName = configurationName; } diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorExtensionAssemblyNameAttribute.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorExtensionAssemblyNameAttribute.cs index 79a2edc3782b..8033bc0be899 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorExtensionAssemblyNameAttribute.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorExtensionAssemblyNameAttribute.cs @@ -21,15 +21,8 @@ public sealed class RazorExtensionAssemblyNameAttribute : Attribute /// The assembly name of the extension. public RazorExtensionAssemblyNameAttribute(string extensionName, string assemblyName) { - if (extensionName == null) - { - throw new ArgumentNullException(nameof(extensionName)); - } - - if (assemblyName == null) - { - throw new ArgumentNullException(nameof(assemblyName)); - } + ArgumentNullException.ThrowIfNull(extensionName); + ArgumentNullException.ThrowIfNull(assemblyName); ExtensionName = extensionName; AssemblyName = assemblyName; diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorLanguageVersionAttribute.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorLanguageVersionAttribute.cs index bb75c576ab7f..f3e37db275af 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorLanguageVersionAttribute.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorLanguageVersionAttribute.cs @@ -20,10 +20,7 @@ public sealed class RazorLanguageVersionAttribute : Attribute /// The language version of Razor public RazorLanguageVersionAttribute(string languageVersion) { - if (languageVersion == null) - { - throw new ArgumentNullException(nameof(languageVersion)); - } + ArgumentNullException.ThrowIfNull(languageVersion); LanguageVersion = languageVersion; } diff --git a/src/Razor/Razor.Runtime/src/Hosting/RazorSourceChecksumAttribute.cs b/src/Razor/Razor.Runtime/src/Hosting/RazorSourceChecksumAttribute.cs index 8c1c95170c64..138cefbcc24d 100644 --- a/src/Razor/Razor.Runtime/src/Hosting/RazorSourceChecksumAttribute.cs +++ b/src/Razor/Razor.Runtime/src/Hosting/RazorSourceChecksumAttribute.cs @@ -27,20 +27,9 @@ public sealed class RazorSourceChecksumAttribute : Attribute, IRazorSourceChecks /// The identifier associated with this thumbprint. public RazorSourceChecksumAttribute(string checksumAlgorithm, string checksum, string identifier) { - if (checksumAlgorithm == null) - { - throw new ArgumentNullException(nameof(checksumAlgorithm)); - } - - if (checksum == null) - { - throw new ArgumentNullException(nameof(checksum)); - } - - if (identifier == null) - { - throw new ArgumentNullException(nameof(identifier)); - } + ArgumentNullException.ThrowIfNull(checksumAlgorithm); + ArgumentNullException.ThrowIfNull(checksum); + ArgumentNullException.ThrowIfNull(identifier); ChecksumAlgorithm = checksumAlgorithm; Checksum = checksum; diff --git a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs index 46685a41769e..6e0c73f35e00 100644 --- a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs +++ b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs @@ -57,15 +57,8 @@ public TagHelperExecutionContext( Action startTagHelperWritingScope, Func endTagHelperWritingScope) { - if (startTagHelperWritingScope == null) - { - throw new ArgumentNullException(nameof(startTagHelperWritingScope)); - } - - if (endTagHelperWritingScope == null) - { - throw new ArgumentNullException(nameof(endTagHelperWritingScope)); - } + ArgumentNullException.ThrowIfNull(startTagHelperWritingScope); + ArgumentNullException.ThrowIfNull(endTagHelperWritingScope); _tagHelpers = new List(); _allAttributes = new TagHelperAttributeList(); @@ -116,10 +109,7 @@ public TagHelperExecutionContext( /// The tag helper to track. public void Add(ITagHelper tagHelper) { - if (tagHelper == null) - { - throw new ArgumentNullException(nameof(tagHelper)); - } + ArgumentNullException.ThrowIfNull(tagHelper); _tagHelpers.Add(tagHelper); } @@ -132,10 +122,7 @@ public void Add(ITagHelper tagHelper) /// The value style of the attribute. public void AddHtmlAttribute(string name, object value, HtmlAttributeValueStyle valueStyle) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var attribute = new TagHelperAttribute(name, value, valueStyle); AddHtmlAttribute(attribute); @@ -147,10 +134,7 @@ public void AddHtmlAttribute(string name, object value, HtmlAttributeValueStyle /// The to track. public void AddHtmlAttribute(TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); Output.Attributes.Add(attribute); _allAttributes.Add(attribute); @@ -164,10 +148,7 @@ public void AddHtmlAttribute(TagHelperAttribute attribute) /// The value style of the attribute. public void AddTagHelperAttribute(string name, object value, HtmlAttributeValueStyle valueStyle) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var attribute = new TagHelperAttribute(name, value, valueStyle); _allAttributes.Add(attribute); @@ -179,10 +160,7 @@ public void AddTagHelperAttribute(string name, object value, HtmlAttributeValueS /// The bound attribute. public void AddTagHelperAttribute(TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); _allAttributes.Add(attribute); } @@ -202,25 +180,10 @@ public void Reinitialize( string uniqueId, Func executeChildContentAsync) { - if (tagName == null) - { - throw new ArgumentNullException(nameof(tagName)); - } - - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } - - if (uniqueId == null) - { - throw new ArgumentNullException(nameof(uniqueId)); - } - - if (executeChildContentAsync == null) - { - throw new ArgumentNullException(nameof(executeChildContentAsync)); - } + ArgumentNullException.ThrowIfNull(tagName); + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(uniqueId); + ArgumentNullException.ThrowIfNull(executeChildContentAsync); Items = items; _executeChildContentAsync = executeChildContentAsync; diff --git a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperRunner.cs b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperRunner.cs index 49553c793f20..5742bb7b8900 100644 --- a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperRunner.cs +++ b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperRunner.cs @@ -20,10 +20,7 @@ public class TagHelperRunner /// 's s. public Task RunAsync(TagHelperExecutionContext executionContext) { - if (executionContext == null) - { - throw new ArgumentNullException(nameof(executionContext)); - } + ArgumentNullException.ThrowIfNull(executionContext); var tagHelperContext = executionContext.Context; var tagHelpers = CollectionsMarshal.AsSpan(executionContext.TagHelperList); diff --git a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperScopeManager.cs b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperScopeManager.cs index 2c676d1e290c..a83ce58675de 100644 --- a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperScopeManager.cs +++ b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperScopeManager.cs @@ -26,15 +26,8 @@ public TagHelperScopeManager( Action startTagHelperWritingScope, Func endTagHelperWritingScope) { - if (startTagHelperWritingScope == null) - { - throw new ArgumentNullException(nameof(startTagHelperWritingScope)); - } - - if (endTagHelperWritingScope == null) - { - throw new ArgumentNullException(nameof(endTagHelperWritingScope)); - } + ArgumentNullException.ThrowIfNull(startTagHelperWritingScope); + ArgumentNullException.ThrowIfNull(endTagHelperWritingScope); _executionContextPool = new ExecutionContextPool(startTagHelperWritingScope, endTagHelperWritingScope); } @@ -53,20 +46,9 @@ public TagHelperExecutionContext Begin( string uniqueId, Func executeChildContentAsync) { - if (tagName == null) - { - throw new ArgumentNullException(nameof(tagName)); - } - - if (uniqueId == null) - { - throw new ArgumentNullException(nameof(uniqueId)); - } - - if (executeChildContentAsync == null) - { - throw new ArgumentNullException(nameof(executeChildContentAsync)); - } + ArgumentNullException.ThrowIfNull(tagName); + ArgumentNullException.ThrowIfNull(uniqueId); + ArgumentNullException.ThrowIfNull(executeChildContentAsync); IDictionary items; var parentExecutionContext = _executionContextPool.Current; diff --git a/src/Razor/Razor/src/TagHelpers/DefaultTagHelperContent.cs b/src/Razor/Razor/src/TagHelpers/DefaultTagHelperContent.cs index 4852c89bf9bd..7c3a4bc9eec6 100644 --- a/src/Razor/Razor/src/TagHelpers/DefaultTagHelperContent.cs +++ b/src/Razor/Razor/src/TagHelpers/DefaultTagHelperContent.cs @@ -95,10 +95,7 @@ public override TagHelperContent AppendHtml(string encoded) /// public override void CopyTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); if (!_hasContent) { @@ -121,10 +118,7 @@ public override void CopyTo(IHtmlContentBuilder destination) /// public override void MoveTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); if (!_hasContent) { @@ -184,15 +178,8 @@ public override string GetContent(HtmlEncoder encoder) /// public override void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); if (!_hasContent) { diff --git a/src/Razor/Razor/src/TagHelpers/NullHtmlEncoder.cs b/src/Razor/Razor/src/TagHelpers/NullHtmlEncoder.cs index 8204090ae348..c6d56b5d4f46 100644 --- a/src/Razor/Razor/src/TagHelpers/NullHtmlEncoder.cs +++ b/src/Razor/Razor/src/TagHelpers/NullHtmlEncoder.cs @@ -31,10 +31,7 @@ private NullHtmlEncoder() /// public override string Encode(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); return value; } @@ -42,15 +39,8 @@ public override string Encode(string value) /// public override void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(value); if (characterCount == 0) { @@ -63,15 +53,8 @@ public override void Encode(TextWriter output, char[] value, int startIndex, int /// public override void Encode(TextWriter output, string value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(value); if (characterCount == 0) { diff --git a/src/Razor/Razor/src/TagHelpers/OutputElementHintAttribute.cs b/src/Razor/Razor/src/TagHelpers/OutputElementHintAttribute.cs index fb1414846d73..9b00c6bf2d85 100644 --- a/src/Razor/Razor/src/TagHelpers/OutputElementHintAttribute.cs +++ b/src/Razor/Razor/src/TagHelpers/OutputElementHintAttribute.cs @@ -17,10 +17,7 @@ public sealed class OutputElementHintAttribute : Attribute /// public OutputElementHintAttribute(string outputElement) { - if (outputElement == null) - { - throw new ArgumentNullException(nameof(outputElement)); - } + ArgumentNullException.ThrowIfNull(outputElement); OutputElement = outputElement; } diff --git a/src/Razor/Razor/src/TagHelpers/ReadOnlyTagHelperAttributeList.cs b/src/Razor/Razor/src/TagHelpers/ReadOnlyTagHelperAttributeList.cs index 6f57d8293ca4..ebd5efd2ac46 100644 --- a/src/Razor/Razor/src/TagHelpers/ReadOnlyTagHelperAttributeList.cs +++ b/src/Razor/Razor/src/TagHelpers/ReadOnlyTagHelperAttributeList.cs @@ -44,10 +44,7 @@ public TagHelperAttribute this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); // Perf: Avoid allocating enumerator var items = Items; @@ -96,10 +93,7 @@ public bool ContainsName(string name) /// is compared case-insensitively. public bool TryGetAttribute(string name, out TagHelperAttribute attribute) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); attribute = this[name]; @@ -119,10 +113,7 @@ public bool TryGetAttribute(string name, out TagHelperAttribute attribute) /// is compared case-insensitively. public bool TryGetAttributes(string name, out IReadOnlyList attributes) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); // Perf: Avoid allocating enumerator List matchedAttributes = null; @@ -157,10 +148,7 @@ public bool TryGetAttributes(string name, out IReadOnlyList /// if found; otherwise, -1. public int IndexOfName(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); var items = Items; // Read interface .Count once rather than per iteration @@ -186,10 +174,7 @@ public int IndexOfName(string name) /// . protected static bool NameEquals(string name, TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); return string.Equals(name, attribute.Name, StringComparison.OrdinalIgnoreCase); } diff --git a/src/Razor/Razor/src/TagHelpers/TagHelperAttribute.cs b/src/Razor/Razor/src/TagHelpers/TagHelperAttribute.cs index 4b82f3e4ce7a..99029539787f 100644 --- a/src/Razor/Razor/src/TagHelpers/TagHelperAttribute.cs +++ b/src/Razor/Razor/src/TagHelpers/TagHelperAttribute.cs @@ -44,10 +44,7 @@ public TagHelperAttribute(string name, object value) /// is ignored when this instance is rendered. public TagHelperAttribute(string name, object value, HtmlAttributeValueStyle valueStyle) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; Value = value; @@ -83,15 +80,8 @@ public bool Equals(TagHelperAttribute other) /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); writer.Write(Name); @@ -126,10 +116,7 @@ public void WriteTo(TextWriter writer, HtmlEncoder encoder) /// public void CopyTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); destination.AppendHtml(Name); @@ -174,10 +161,7 @@ public void CopyTo(IHtmlContentBuilder destination) /// public void MoveTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); destination.AppendHtml(Name); diff --git a/src/Razor/Razor/src/TagHelpers/TagHelperAttributeList.cs b/src/Razor/Razor/src/TagHelpers/TagHelperAttributeList.cs index a99e796cecc7..93ab7b88d774 100644 --- a/src/Razor/Razor/src/TagHelpers/TagHelperAttributeList.cs +++ b/src/Razor/Razor/src/TagHelpers/TagHelperAttributeList.cs @@ -24,10 +24,7 @@ public TagHelperAttributeList() public TagHelperAttributeList(IEnumerable attributes) : base(new List(attributes)) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); } /// @@ -38,10 +35,7 @@ public TagHelperAttributeList(IEnumerable attributes) public TagHelperAttributeList(List attributes) : base(attributes) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(attributes); } /// @@ -56,10 +50,7 @@ public TagHelperAttributeList(List attributes) } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); Items[index] = value; } @@ -96,10 +87,7 @@ public void SetAttribute(string name, object value) /// case-insensitively. public void SetAttribute(TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); var attributeReplaced = false; @@ -147,10 +135,7 @@ public void Add(string name, object value) /// public void Add(TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); Items.Add(attribute); } @@ -158,10 +143,7 @@ public void Add(TagHelperAttribute attribute) /// public void Insert(int index, TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); Items.Insert(index, attribute); } @@ -172,10 +154,7 @@ public void Insert(int index, TagHelperAttribute attribute) /// public bool Remove(TagHelperAttribute attribute) { - if (attribute == null) - { - throw new ArgumentNullException(nameof(attribute)); - } + ArgumentNullException.ThrowIfNull(attribute); return Items.Remove(attribute); } @@ -199,10 +178,7 @@ public void RemoveAt(int index) /// is compared case-insensitively. public bool RemoveAll(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); // Perf: Avoid allocating enumerator var removedAtLeastOne = false; diff --git a/src/Razor/Razor/src/TagHelpers/TagHelperContext.cs b/src/Razor/Razor/src/TagHelpers/TagHelperContext.cs index 0920e980b475..f3d716125eed 100644 --- a/src/Razor/Razor/src/TagHelpers/TagHelperContext.cs +++ b/src/Razor/Razor/src/TagHelpers/TagHelperContext.cs @@ -24,10 +24,7 @@ public TagHelperContext( IDictionary items, string uniqueId) : this(allAttributes, items, uniqueId) { - if (tagName == null) - { - throw new ArgumentNullException(nameof(tagName)); - } + ArgumentNullException.ThrowIfNull(tagName); TagName = tagName; } @@ -44,20 +41,9 @@ public TagHelperContext( IDictionary items, string uniqueId) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } - - if (uniqueId == null) - { - throw new ArgumentNullException(nameof(uniqueId)); - } - - if (allAttributes == null) - { - throw new ArgumentNullException(nameof(allAttributes)); - } + ArgumentNullException.ThrowIfNull(items); + ArgumentNullException.ThrowIfNull(uniqueId); + ArgumentNullException.ThrowIfNull(allAttributes); _allAttributes = allAttributes; Items = items; diff --git a/src/Razor/Razor/src/TagHelpers/TagHelperOutput.cs b/src/Razor/Razor/src/TagHelpers/TagHelperOutput.cs index d8cd1c9b763a..a91fd8a88f6c 100644 --- a/src/Razor/Razor/src/TagHelpers/TagHelperOutput.cs +++ b/src/Razor/Razor/src/TagHelpers/TagHelperOutput.cs @@ -42,15 +42,8 @@ public TagHelperOutput( TagHelperAttributeList attributes, Func> getChildContentAsync) { - if (getChildContentAsync == null) - { - throw new ArgumentNullException(nameof(getChildContentAsync)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(getChildContentAsync); + ArgumentNullException.ThrowIfNull(attributes); TagName = tagName; _getChildContentAsync = getChildContentAsync; @@ -117,10 +110,7 @@ public TagHelperContent Content } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _content = value; } @@ -288,10 +278,7 @@ public Task GetChildContentAsync(bool useCachedResult, HtmlEnc void IHtmlContentContainer.CopyTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); _preElement?.CopyTo(destination); @@ -340,10 +327,7 @@ void IHtmlContentContainer.CopyTo(IHtmlContentBuilder destination) void IHtmlContentContainer.MoveTo(IHtmlContentBuilder destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); _preElement?.MoveTo(destination); @@ -397,15 +381,8 @@ void IHtmlContentContainer.MoveTo(IHtmlContentBuilder destination) /// public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (encoder == null) - { - throw new ArgumentNullException(nameof(encoder)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(encoder); _preElement?.WriteTo(writer, encoder); diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs index 1d535c017b46..89513286ee1b 100644 --- a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs +++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs @@ -279,10 +279,7 @@ protected virtual async Task FinishResponseAsync() /// protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) { - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullException.ThrowIfNull(user); properties = properties ?? new AuthenticationProperties(); diff --git a/src/Security/Authentication/Cookies/src/CookieSlidingExpirationContext.cs b/src/Security/Authentication/Cookies/src/CookieSlidingExpirationContext.cs index 5c6cb89d125d..35f12ae4e337 100644 --- a/src/Security/Authentication/Cookies/src/CookieSlidingExpirationContext.cs +++ b/src/Security/Authentication/Cookies/src/CookieSlidingExpirationContext.cs @@ -23,10 +23,7 @@ public CookieSlidingExpirationContext(HttpContext context, AuthenticationScheme AuthenticationTicket ticket, TimeSpan elapsedTime, TimeSpan remainingTime) : base(context, scheme, options, ticket?.Properties) { - if (ticket == null) - { - throw new ArgumentNullException(nameof(ticket)); - } + ArgumentNullException.ThrowIfNull(ticket); Principal = ticket.Principal; ElapsedTime = elapsedTime; diff --git a/src/Security/Authentication/Cookies/src/CookieValidatePrincipalContext.cs b/src/Security/Authentication/Cookies/src/CookieValidatePrincipalContext.cs index 77e34db48b58..e979c7b6ea90 100644 --- a/src/Security/Authentication/Cookies/src/CookieValidatePrincipalContext.cs +++ b/src/Security/Authentication/Cookies/src/CookieValidatePrincipalContext.cs @@ -21,10 +21,7 @@ public class CookieValidatePrincipalContext : PrincipalContextA reference to this instance after the operation has completed. public static IApplicationBuilder UseAuthentication(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); app.Properties[AuthenticationMiddlewareSetKey] = true; return app.UseMiddleware(); diff --git a/src/Security/Authentication/Core/src/AuthenticationHandler.cs b/src/Security/Authentication/Core/src/AuthenticationHandler.cs index 909d0f4260b0..bc5535ee88c4 100644 --- a/src/Security/Authentication/Core/src/AuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/AuthenticationHandler.cs @@ -123,14 +123,8 @@ protected AuthenticationHandler(IOptionsMonitor options, ILoggerFactor /// public async Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { - if (scheme == null) - { - throw new ArgumentNullException(nameof(scheme)); - } - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(scheme); + ArgumentNullException.ThrowIfNull(context); Scheme = scheme; Context = context; diff --git a/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs b/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs index bbf18870b966..d6fe49214401 100644 --- a/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs +++ b/src/Security/Authentication/Core/src/AuthenticationMiddleware.cs @@ -21,14 +21,8 @@ public class AuthenticationMiddleware /// The . public AuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes) { - if (next == null) - { - throw new ArgumentNullException(nameof(next)); - } - if (schemes == null) - { - throw new ArgumentNullException(nameof(schemes)); - } + ArgumentNullException.ThrowIfNull(next); + ArgumentNullException.ThrowIfNull(schemes); _next = next; Schemes = schemes; diff --git a/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs b/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs index a318eb3a30d2..15ff9cf841b6 100644 --- a/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs +++ b/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs @@ -18,10 +18,7 @@ public static class AuthenticationServiceCollectionExtensions /// A that can be used to further configure authentication. public static AuthenticationBuilder AddAuthentication(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddAuthenticationCore(); services.AddDataProtection(); @@ -50,15 +47,8 @@ public static AuthenticationBuilder AddAuthentication(this IServiceCollection se /// A that can be used to further configure authentication. public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); var builder = services.AddAuthentication(); services.Configure(configureOptions); diff --git a/src/Security/Authentication/Core/src/Events/BaseContext.cs b/src/Security/Authentication/Core/src/Events/BaseContext.cs index c3a4bc96e617..2eef944595df 100644 --- a/src/Security/Authentication/Core/src/Events/BaseContext.cs +++ b/src/Security/Authentication/Core/src/Events/BaseContext.cs @@ -18,18 +18,9 @@ public abstract class BaseContext where TOptions : AuthenticationSchem /// The authentication options associated with the scheme. protected BaseContext(HttpContext context, AuthenticationScheme scheme, TOptions options) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (scheme == null) - { - throw new ArgumentNullException(nameof(scheme)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(scheme); + ArgumentNullException.ThrowIfNull(options); HttpContext = context; Scheme = scheme; diff --git a/src/Security/Authentication/Core/src/HandleRequestResult.cs b/src/Security/Authentication/Core/src/HandleRequestResult.cs index 3b77e0e3a8de..b4c73e45c713 100644 --- a/src/Security/Authentication/Core/src/HandleRequestResult.cs +++ b/src/Security/Authentication/Core/src/HandleRequestResult.cs @@ -31,10 +31,7 @@ public class HandleRequestResult : AuthenticateResult /// The result. public static new HandleRequestResult Success(AuthenticationTicket ticket) { - if (ticket == null) - { - throw new ArgumentNullException(nameof(ticket)); - } + ArgumentNullException.ThrowIfNull(ticket); return new HandleRequestResult() { Ticket = ticket, Properties = ticket.Properties }; } diff --git a/src/Security/Authentication/Core/src/PropertiesSerializer.cs b/src/Security/Authentication/Core/src/PropertiesSerializer.cs index 630f41f9325e..6d00508d9d30 100644 --- a/src/Security/Authentication/Core/src/PropertiesSerializer.cs +++ b/src/Security/Authentication/Core/src/PropertiesSerializer.cs @@ -44,15 +44,8 @@ public virtual byte[] Serialize(AuthenticationProperties model) /// public virtual void Write(BinaryWriter writer, AuthenticationProperties properties) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(properties); writer.Write(FormatVersion); writer.Write(properties.Items.Count); @@ -67,10 +60,7 @@ public virtual void Write(BinaryWriter writer, AuthenticationProperties properti /// public virtual AuthenticationProperties? Read(BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (reader.ReadInt32() != FormatVersion) { diff --git a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs index b78c9d0cd349..e7ee941e0c74 100644 --- a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs @@ -215,10 +215,7 @@ protected override Task HandleForbiddenAsync(AuthenticationProperties properties /// protected virtual void GenerateCorrelationId(AuthenticationProperties properties) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } + ArgumentNullException.ThrowIfNull(properties); var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); @@ -240,10 +237,7 @@ protected virtual void GenerateCorrelationId(AuthenticationProperties properties /// protected virtual bool ValidateCorrelationId(AuthenticationProperties properties) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } + ArgumentNullException.ThrowIfNull(properties); if (!properties.Items.TryGetValue(CorrelationProperty, out var correlationId)) { diff --git a/src/Security/Authentication/Core/src/TicketSerializer.cs b/src/Security/Authentication/Core/src/TicketSerializer.cs index 3fd0c6f17704..ffe2f18c578a 100644 --- a/src/Security/Authentication/Core/src/TicketSerializer.cs +++ b/src/Security/Authentication/Core/src/TicketSerializer.cs @@ -52,15 +52,8 @@ public virtual byte[] Serialize(AuthenticationTicket ticket) /// The . public virtual void Write(BinaryWriter writer, AuthenticationTicket ticket) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (ticket == null) - { - throw new ArgumentNullException(nameof(ticket)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(ticket); writer.Write(FormatVersion); writer.Write(ticket.AuthenticationScheme); @@ -84,15 +77,8 @@ public virtual void Write(BinaryWriter writer, AuthenticationTicket ticket) /// The . protected virtual void WriteIdentity(BinaryWriter writer, ClaimsIdentity identity) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(identity); var authenticationType = identity.AuthenticationType ?? string.Empty; @@ -133,15 +119,8 @@ protected virtual void WriteIdentity(BinaryWriter writer, ClaimsIdentity identit /// protected virtual void WriteClaim(BinaryWriter writer, Claim claim) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(claim); WriteWithDefault(writer, claim.Type, claim.Subject?.NameClaimType ?? ClaimsIdentity.DefaultNameClaimType); writer.Write(claim.Value); @@ -166,10 +145,7 @@ protected virtual void WriteClaim(BinaryWriter writer, Claim claim) /// The if the format is supported, otherwise . public virtual AuthenticationTicket? Read(BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (reader.ReadInt32() != FormatVersion) { @@ -204,10 +180,7 @@ protected virtual void WriteClaim(BinaryWriter writer, Claim claim) /// The read . protected virtual ClaimsIdentity ReadIdentity(BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); var authenticationType = reader.ReadString(); var nameClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultNameClaimType); @@ -251,15 +224,8 @@ protected virtual ClaimsIdentity ReadIdentity(BinaryReader reader) /// The read . protected virtual Claim ReadClaim(BinaryReader reader, ClaimsIdentity identity) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(identity); var type = ReadWithDefault(reader, identity.NameClaimType); var value = reader.ReadString(); diff --git a/src/Security/Authentication/Negotiate/src/NegotiateOptions.cs b/src/Security/Authentication/Negotiate/src/NegotiateOptions.cs index 4a92b6b41799..e29db02ac6e9 100644 --- a/src/Security/Authentication/Negotiate/src/NegotiateOptions.cs +++ b/src/Security/Authentication/Negotiate/src/NegotiateOptions.cs @@ -60,10 +60,7 @@ public void EnableLdap(string domain) /// public void EnableLdap(Action configureSettings) { - if (configureSettings == null) - { - throw new ArgumentNullException(nameof(configureSettings)); - } + ArgumentNullException.ThrowIfNull(configureSettings); LdapSettings.EnableLdapClaimResolution = true; configureSettings(LdapSettings); diff --git a/src/Security/Authentication/OAuth/src/ClaimActionCollectionMapExtensions.cs b/src/Security/Authentication/OAuth/src/ClaimActionCollectionMapExtensions.cs index 2c9f5a851b91..961cf7d6d138 100644 --- a/src/Security/Authentication/OAuth/src/ClaimActionCollectionMapExtensions.cs +++ b/src/Security/Authentication/OAuth/src/ClaimActionCollectionMapExtensions.cs @@ -21,10 +21,7 @@ public static class ClaimActionCollectionMapExtensions /// The top level key to look for in the json user data. public static void MapJsonKey(this ClaimActionCollection collection, string claimType, string jsonKey) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.MapJsonKey(claimType, jsonKey, ClaimValueTypes.String); } @@ -39,10 +36,7 @@ public static void MapJsonKey(this ClaimActionCollection collection, string clai /// The value to use for Claim.ValueType when creating a Claim. public static void MapJsonKey(this ClaimActionCollection collection, string claimType, string jsonKey, string valueType) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.Add(new JsonKeyClaimAction(claimType, valueType, jsonKey)); } @@ -57,10 +51,7 @@ public static void MapJsonKey(this ClaimActionCollection collection, string clai /// The second level key to look for in the json user data. public static void MapJsonSubKey(this ClaimActionCollection collection, string claimType, string jsonKey, string subKey) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.MapJsonSubKey(claimType, jsonKey, subKey, ClaimValueTypes.String); } @@ -76,10 +67,7 @@ public static void MapJsonSubKey(this ClaimActionCollection collection, string c /// The value to use for Claim.ValueType when creating a Claim. public static void MapJsonSubKey(this ClaimActionCollection collection, string claimType, string jsonKey, string subKey, string valueType) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.Add(new JsonSubKeyClaimAction(claimType, valueType, jsonKey, subKey)); } @@ -93,10 +81,7 @@ public static void MapJsonSubKey(this ClaimActionCollection collection, string c /// The Func that will be called to select value from the given json user data. public static void MapCustomJson(this ClaimActionCollection collection, string claimType, Func resolver) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.MapCustomJson(claimType, ClaimValueTypes.String, resolver); } @@ -111,10 +96,7 @@ public static void MapCustomJson(this ClaimActionCollection collection, string c /// The Func that will be called to select value from the given json user data. public static void MapCustomJson(this ClaimActionCollection collection, string claimType, string valueType, Func resolver) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.Add(new CustomJsonClaimAction(claimType, valueType, resolver)); } @@ -125,10 +107,7 @@ public static void MapCustomJson(this ClaimActionCollection collection, string c /// The . public static void MapAll(this ClaimActionCollection collection) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.Clear(); collection.Add(new MapAllClaimsAction()); @@ -141,10 +120,7 @@ public static void MapAll(this ClaimActionCollection collection) /// The types to exclude. public static void MapAllExcept(this ClaimActionCollection collection, params string[] exclusions) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.MapAll(); collection.DeleteClaims(exclusions); @@ -157,10 +133,7 @@ public static void MapAllExcept(this ClaimActionCollection collection, params st /// The claim type to delete public static void DeleteClaim(this ClaimActionCollection collection, string claimType) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); collection.Add(new DeleteClaimAction(claimType)); } @@ -172,15 +145,8 @@ public static void DeleteClaim(this ClaimActionCollection collection, string cla /// The claim types to delete. public static void DeleteClaims(this ClaimActionCollection collection, params string[] claimTypes) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (claimTypes == null) - { - throw new ArgumentNullException(nameof(claimTypes)); - } + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(claimTypes); foreach (var claimType in claimTypes) { diff --git a/src/Security/Authentication/OAuth/src/Events/OAuthCreatingTicketContext.cs b/src/Security/Authentication/OAuth/src/Events/OAuthCreatingTicketContext.cs index 0ad93ee72ecc..a927ff3f6af7 100644 --- a/src/Security/Authentication/OAuth/src/Events/OAuthCreatingTicketContext.cs +++ b/src/Security/Authentication/OAuth/src/Events/OAuthCreatingTicketContext.cs @@ -36,15 +36,8 @@ public OAuthCreatingTicketContext( JsonElement user) : base(context, scheme, options) { - if (backchannel == null) - { - throw new ArgumentNullException(nameof(backchannel)); - } - - if (tokens == null) - { - throw new ArgumentNullException(nameof(tokens)); - } + ArgumentNullException.ThrowIfNull(backchannel); + ArgumentNullException.ThrowIfNull(tokens); TokenResponse = tokens; Backchannel = backchannel; diff --git a/src/Security/Authentication/OAuth/src/OAuthPostConfigureOptions.cs b/src/Security/Authentication/OAuth/src/OAuthPostConfigureOptions.cs index 15fcb52c1dfa..64bd258a13ae 100644 --- a/src/Security/Authentication/OAuth/src/OAuthPostConfigureOptions.cs +++ b/src/Security/Authentication/OAuth/src/OAuthPostConfigureOptions.cs @@ -30,10 +30,7 @@ public OAuthPostConfigureOptions(IDataProtectionProvider dataProtection) /// public void PostConfigure(string? name, TOptions options) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); options.DataProtectionProvider = options.DataProtectionProvider ?? _dp; if (options.Backchannel == null) diff --git a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectPostConfigureOptions.cs b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectPostConfigureOptions.cs index 2364d0c6080c..4a75bd64a565 100644 --- a/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectPostConfigureOptions.cs +++ b/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectPostConfigureOptions.cs @@ -33,10 +33,7 @@ public OpenIdConnectPostConfigureOptions(IDataProtectionProvider dataProtection) /// The options instance to configure. public void PostConfigure(string? name, OpenIdConnectOptions options) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); options.DataProtectionProvider = options.DataProtectionProvider ?? _dp; diff --git a/src/Security/Authentication/Twitter/src/Messages/RequestTokenSerializer.cs b/src/Security/Authentication/Twitter/src/Messages/RequestTokenSerializer.cs index bea36f3d1a0b..1c044b11a263 100644 --- a/src/Security/Authentication/Twitter/src/Messages/RequestTokenSerializer.cs +++ b/src/Security/Authentication/Twitter/src/Messages/RequestTokenSerializer.cs @@ -51,15 +51,8 @@ public virtual byte[] Serialize(RequestToken model) /// The token to write public static void Write(BinaryWriter writer, RequestToken token) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (token == null) - { - throw new ArgumentNullException(nameof(token)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(token); writer.Write(FormatVersion); writer.Write(token.Token); @@ -75,10 +68,7 @@ public static void Write(BinaryWriter writer, RequestToken token) /// The token public static RequestToken? Read(BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); if (reader.ReadInt32() != FormatVersion) { diff --git a/src/Security/Authentication/Twitter/src/TwitterPostConfigureOptions.cs b/src/Security/Authentication/Twitter/src/TwitterPostConfigureOptions.cs index 5e1d7199e9dc..f9c0e0a69ec2 100644 --- a/src/Security/Authentication/Twitter/src/TwitterPostConfigureOptions.cs +++ b/src/Security/Authentication/Twitter/src/TwitterPostConfigureOptions.cs @@ -30,10 +30,7 @@ public TwitterPostConfigureOptions(IDataProtectionProvider dataProtection) /// The options instance to configure. public void PostConfigure(string? name, TwitterOptions options) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); options.DataProtectionProvider = options.DataProtectionProvider ?? _dp; diff --git a/src/Security/Authentication/WsFederation/src/WsFederationPostConfigureOptions.cs b/src/Security/Authentication/WsFederation/src/WsFederationPostConfigureOptions.cs index ce2137e5f2c7..ffc22fbf7e68 100644 --- a/src/Security/Authentication/WsFederation/src/WsFederationPostConfigureOptions.cs +++ b/src/Security/Authentication/WsFederation/src/WsFederationPostConfigureOptions.cs @@ -33,10 +33,7 @@ public WsFederationPostConfigureOptions(IDataProtectionProvider dataProtection) /// The options instance to configure. public void PostConfigure(string? name, WsFederationOptions options) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); options.DataProtectionProvider = options.DataProtectionProvider ?? _dp; diff --git a/src/Security/Authorization/Core/src/AssertionRequirement.cs b/src/Security/Authorization/Core/src/AssertionRequirement.cs index 15865bf056aa..8d2674c40bc5 100644 --- a/src/Security/Authorization/Core/src/AssertionRequirement.cs +++ b/src/Security/Authorization/Core/src/AssertionRequirement.cs @@ -3,6 +3,7 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization.Infrastructure; @@ -23,10 +24,7 @@ public class AssertionRequirement : IAuthorizationHandler, IAuthorizationRequire /// Function that is called to handle this requirement. public AssertionRequirement(Func handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullThrowHelper.ThrowIfNull(handler); Handler = context => Task.FromResult(handler(context)); } @@ -37,10 +35,7 @@ public AssertionRequirement(Func handler) /// Function that is called to handle this requirement. public AssertionRequirement(Func> handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullThrowHelper.ThrowIfNull(handler); Handler = handler; } diff --git a/src/Security/Authorization/Core/src/AuthorizationBuilder.cs b/src/Security/Authorization/Core/src/AuthorizationBuilder.cs index 793d2ab2709e..c8fc77281c09 100644 --- a/src/Security/Authorization/Core/src/AuthorizationBuilder.cs +++ b/src/Security/Authorization/Core/src/AuthorizationBuilder.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Authorization; @@ -107,10 +108,7 @@ public virtual AuthorizationBuilder AddDefaultPolicy(string name, AuthorizationP /// The builder. public virtual AuthorizationBuilder AddDefaultPolicy(string name, Action configurePolicy) { - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullThrowHelper.ThrowIfNull(configurePolicy); var policyBuilder = new AuthorizationPolicyBuilder(); configurePolicy(policyBuilder); @@ -137,10 +135,7 @@ public virtual AuthorizationBuilder AddFallbackPolicy(string name, Authorization /// The builder. public virtual AuthorizationBuilder AddFallbackPolicy(string name, Action configurePolicy) { - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullThrowHelper.ThrowIfNull(configurePolicy); var policyBuilder = new AuthorizationPolicyBuilder(); configurePolicy(policyBuilder); diff --git a/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs b/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs index f0924fcb6890..f9e451fd0dc6 100644 --- a/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs +++ b/src/Security/Authorization/Core/src/AuthorizationHandlerContext.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -29,10 +30,7 @@ public AuthorizationHandlerContext( ClaimsPrincipal user, object? resource) { - if (requirements == null) - { - throw new ArgumentNullException(nameof(requirements)); - } + ArgumentNullThrowHelper.ThrowIfNull(requirements); Requirements = requirements; User = user; diff --git a/src/Security/Authorization/Core/src/AuthorizationOptions.cs b/src/Security/Authorization/Core/src/AuthorizationOptions.cs index be317aa553da..31edaf2f075b 100644 --- a/src/Security/Authorization/Core/src/AuthorizationOptions.cs +++ b/src/Security/Authorization/Core/src/AuthorizationOptions.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -47,15 +48,8 @@ public class AuthorizationOptions /// The authorization policy. public void AddPolicy(string name, AuthorizationPolicy policy) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(policy); PolicyMap[name] = Task.FromResult(policy); } @@ -67,15 +61,8 @@ public void AddPolicy(string name, AuthorizationPolicy policy) /// The delegate that will be used to build the policy. public void AddPolicy(string name, Action configurePolicy) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(configurePolicy); var policyBuilder = new AuthorizationPolicyBuilder(); configurePolicy(policyBuilder); @@ -89,10 +76,7 @@ public void AddPolicy(string name, Action configureP /// The policy for the specified name, or null if a policy with the name does not exist. public AuthorizationPolicy? GetPolicy(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); if (PolicyMap.TryGetValue(name, out var value)) { @@ -104,10 +88,7 @@ public void AddPolicy(string name, Action configureP internal Task GetPolicyTask(string name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); if (PolicyMap.TryGetValue(name, out var value)) { diff --git a/src/Security/Authorization/Core/src/AuthorizationPolicy.cs b/src/Security/Authorization/Core/src/AuthorizationPolicy.cs index 044cd96bbad3..c1b614003f2c 100644 --- a/src/Security/Authorization/Core/src/AuthorizationPolicy.cs +++ b/src/Security/Authorization/Core/src/AuthorizationPolicy.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -27,15 +28,8 @@ public class AuthorizationPolicy /// public AuthorizationPolicy(IEnumerable requirements, IEnumerable authenticationSchemes) { - if (requirements == null) - { - throw new ArgumentNullException(nameof(requirements)); - } - - if (authenticationSchemes == null) - { - throw new ArgumentNullException(nameof(authenticationSchemes)); - } + ArgumentNullThrowHelper.ThrowIfNull(requirements); + ArgumentNullThrowHelper.ThrowIfNull(authenticationSchemes); if (!requirements.Any()) { @@ -67,10 +61,7 @@ public AuthorizationPolicy(IEnumerable requirements, /// public static AuthorizationPolicy Combine(params AuthorizationPolicy[] policies) { - if (policies == null) - { - throw new ArgumentNullException(nameof(policies)); - } + ArgumentNullThrowHelper.ThrowIfNull(policies); return Combine((IEnumerable)policies); } @@ -85,10 +76,7 @@ public static AuthorizationPolicy Combine(params AuthorizationPolicy[] policies) /// public static AuthorizationPolicy Combine(IEnumerable policies) { - if (policies == null) - { - throw new ArgumentNullException(nameof(policies)); - } + ArgumentNullThrowHelper.ThrowIfNull(policies); var builder = new AuthorizationPolicyBuilder(); foreach (var policy in policies) @@ -127,15 +115,8 @@ public static AuthorizationPolicy Combine(IEnumerable polic IEnumerable authorizeData, IEnumerable policies) { - if (policyProvider == null) - { - throw new ArgumentNullException(nameof(policyProvider)); - } - - if (authorizeData == null) - { - throw new ArgumentNullException(nameof(authorizeData)); - } + ArgumentNullThrowHelper.ThrowIfNull(policyProvider); + ArgumentNullThrowHelper.ThrowIfNull(authorizeData); var anyPolicies = policies.Any(); diff --git a/src/Security/Authorization/Core/src/AuthorizationPolicyBuilder.cs b/src/Security/Authorization/Core/src/AuthorizationPolicyBuilder.cs index 2ba70e5c9a68..884f739346bb 100644 --- a/src/Security/Authorization/Core/src/AuthorizationPolicyBuilder.cs +++ b/src/Security/Authorization/Core/src/AuthorizationPolicyBuilder.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization.Infrastructure; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -86,10 +87,7 @@ public AuthorizationPolicyBuilder AddRequirements(params IAuthorizationRequireme /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder Combine(AuthorizationPolicy policy) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullThrowHelper.ThrowIfNull(policy); AddAuthenticationSchemes(policy.AuthenticationSchemes.ToArray()); AddRequirements(policy.Requirements.ToArray()); @@ -105,10 +103,7 @@ public AuthorizationPolicyBuilder Combine(AuthorizationPolicy policy) /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireClaim(string claimType, params string[] allowedValues) { - if (claimType == null) - { - throw new ArgumentNullException(nameof(claimType)); - } + ArgumentNullThrowHelper.ThrowIfNull(claimType); return RequireClaim(claimType, (IEnumerable)allowedValues); } @@ -122,10 +117,7 @@ public AuthorizationPolicyBuilder RequireClaim(string claimType, params string[] /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireClaim(string claimType, IEnumerable allowedValues) { - if (claimType == null) - { - throw new ArgumentNullException(nameof(claimType)); - } + ArgumentNullThrowHelper.ThrowIfNull(claimType); Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues)); return this; @@ -139,10 +131,7 @@ public AuthorizationPolicyBuilder RequireClaim(string claimType, IEnumerableA reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireClaim(string claimType) { - if (claimType == null) - { - throw new ArgumentNullException(nameof(claimType)); - } + ArgumentNullThrowHelper.ThrowIfNull(claimType); Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues: null)); return this; @@ -156,10 +145,7 @@ public AuthorizationPolicyBuilder RequireClaim(string claimType) /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireRole(params string[] roles) { - if (roles == null) - { - throw new ArgumentNullException(nameof(roles)); - } + ArgumentNullThrowHelper.ThrowIfNull(roles); return RequireRole((IEnumerable)roles); } @@ -172,10 +158,7 @@ public AuthorizationPolicyBuilder RequireRole(params string[] roles) /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireRole(IEnumerable roles) { - if (roles == null) - { - throw new ArgumentNullException(nameof(roles)); - } + ArgumentNullThrowHelper.ThrowIfNull(roles); Requirements.Add(new RolesAuthorizationRequirement(roles)); return this; @@ -188,10 +171,7 @@ public AuthorizationPolicyBuilder RequireRole(IEnumerable roles) /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireUserName(string userName) { - if (userName == null) - { - throw new ArgumentNullException(nameof(userName)); - } + ArgumentNullThrowHelper.ThrowIfNull(userName); Requirements.Add(new NameAuthorizationRequirement(userName)); return this; @@ -214,10 +194,7 @@ public AuthorizationPolicyBuilder RequireAuthenticatedUser() /// A reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireAssertion(Func handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullThrowHelper.ThrowIfNull(handler); Requirements.Add(new AssertionRequirement(handler)); return this; @@ -230,10 +207,7 @@ public AuthorizationPolicyBuilder RequireAssertion(FuncA reference to this instance after the operation has completed. public AuthorizationPolicyBuilder RequireAssertion(Func> handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullThrowHelper.ThrowIfNull(handler); Requirements.Add(new AssertionRequirement(handler)); return this; diff --git a/src/Security/Authorization/Core/src/AuthorizationServiceCollectionExtensions.cs b/src/Security/Authorization/Core/src/AuthorizationServiceCollectionExtensions.cs index b12f8eaf1c11..273f3c5ff563 100644 --- a/src/Security/Authorization/Core/src/AuthorizationServiceCollectionExtensions.cs +++ b/src/Security/Authorization/Core/src/AuthorizationServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using System; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization.Infrastructure; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection; @@ -20,10 +21,7 @@ public static class AuthorizationServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddAuthorizationCore(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); // These services depend on options, and they are used in Blazor WASM, where options // aren't included by default. @@ -46,15 +44,8 @@ public static IServiceCollection AddAuthorizationCore(this IServiceCollection se /// The so that additional calls can be chained. public static IServiceCollection AddAuthorizationCore(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(configure); services.Configure(configure); return services.AddAuthorizationCore(); diff --git a/src/Security/Authorization/Core/src/AuthorizationServiceExtensions.cs b/src/Security/Authorization/Core/src/AuthorizationServiceExtensions.cs index 976f575d1198..e6d1d364effa 100644 --- a/src/Security/Authorization/Core/src/AuthorizationServiceExtensions.cs +++ b/src/Security/Authorization/Core/src/AuthorizationServiceExtensions.cs @@ -4,6 +4,7 @@ using System; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -25,15 +26,8 @@ public static class AuthorizationServiceExtensions /// public static Task AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object? resource, IAuthorizationRequirement requirement) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (requirement == null) - { - throw new ArgumentNullException(nameof(requirement)); - } + ArgumentNullThrowHelper.ThrowIfNull(service); + ArgumentNullThrowHelper.ThrowIfNull(requirement); return service.AuthorizeAsync(user, resource, new IAuthorizationRequirement[] { requirement }); } @@ -51,15 +45,8 @@ public static Task AuthorizeAsync(this IAuthorizationServic /// public static Task AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object? resource, AuthorizationPolicy policy) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullThrowHelper.ThrowIfNull(service); + ArgumentNullThrowHelper.ThrowIfNull(policy); return service.AuthorizeAsync(user, resource, policy.Requirements); } @@ -76,15 +63,8 @@ public static Task AuthorizeAsync(this IAuthorizationServic /// public static Task AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, AuthorizationPolicy policy) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullThrowHelper.ThrowIfNull(service); + ArgumentNullThrowHelper.ThrowIfNull(policy); return service.AuthorizeAsync(user, resource: null, policy: policy); } @@ -101,15 +81,8 @@ public static Task AuthorizeAsync(this IAuthorizationServic /// public static Task AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, string policyName) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (policyName == null) - { - throw new ArgumentNullException(nameof(policyName)); - } + ArgumentNullThrowHelper.ThrowIfNull(service); + ArgumentNullThrowHelper.ThrowIfNull(policyName); return service.AuthorizeAsync(user, resource: null, policyName: policyName); } diff --git a/src/Security/Authorization/Core/src/ClaimsAuthorizationRequirement.cs b/src/Security/Authorization/Core/src/ClaimsAuthorizationRequirement.cs index 28483292c5da..55ae9b5f0445 100644 --- a/src/Security/Authorization/Core/src/ClaimsAuthorizationRequirement.cs +++ b/src/Security/Authorization/Core/src/ClaimsAuthorizationRequirement.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization.Infrastructure; @@ -24,10 +25,7 @@ public class ClaimsAuthorizationRequirement : AuthorizationHandlerOptional list of claim values. If specified, the claim must match one or more of these values. public ClaimsAuthorizationRequirement(string claimType, IEnumerable? allowedValues) { - if (claimType == null) - { - throw new ArgumentNullException(nameof(claimType)); - } + ArgumentNullThrowHelper.ThrowIfNull(claimType); ClaimType = claimType; AllowedValues = allowedValues; diff --git a/src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs b/src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs index e92dee2a3f31..7ee5612a6d4c 100644 --- a/src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs +++ b/src/Security/Authorization/Core/src/DefaultAuthorizationHandlerProvider.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization; @@ -21,10 +22,7 @@ public class DefaultAuthorizationHandlerProvider : IAuthorizationHandlerProvider /// The s. public DefaultAuthorizationHandlerProvider(IEnumerable handlers) { - if (handlers == null) - { - throw new ArgumentNullException(nameof(handlers)); - } + ArgumentNullThrowHelper.ThrowIfNull(handlers); _handlersTask = Task.FromResult(handlers); } diff --git a/src/Security/Authorization/Core/src/DefaultAuthorizationPolicyProvider.cs b/src/Security/Authorization/Core/src/DefaultAuthorizationPolicyProvider.cs index 1b528742f859..609375c73fc2 100644 --- a/src/Security/Authorization/Core/src/DefaultAuthorizationPolicyProvider.cs +++ b/src/Security/Authorization/Core/src/DefaultAuthorizationPolicyProvider.cs @@ -3,6 +3,7 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Authorization; @@ -23,10 +24,7 @@ public class DefaultAuthorizationPolicyProvider : IAuthorizationPolicyProvider /// The options used to configure this instance. public DefaultAuthorizationPolicyProvider(IOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(options); _options = options.Value; } diff --git a/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs b/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs index 7278dc2d887a..8bc186a2d19c 100644 --- a/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs +++ b/src/Security/Authorization/Core/src/DefaultAuthorizationService.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -33,30 +34,12 @@ public class DefaultAuthorizationService : IAuthorizationService /// The used. public DefaultAuthorizationService(IAuthorizationPolicyProvider policyProvider, IAuthorizationHandlerProvider handlers, ILogger logger, IAuthorizationHandlerContextFactory contextFactory, IAuthorizationEvaluator evaluator, IOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (policyProvider == null) - { - throw new ArgumentNullException(nameof(policyProvider)); - } - if (handlers == null) - { - throw new ArgumentNullException(nameof(handlers)); - } - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - if (contextFactory == null) - { - throw new ArgumentNullException(nameof(contextFactory)); - } - if (evaluator == null) - { - throw new ArgumentNullException(nameof(evaluator)); - } + ArgumentNullThrowHelper.ThrowIfNull(options); + ArgumentNullThrowHelper.ThrowIfNull(policyProvider); + ArgumentNullThrowHelper.ThrowIfNull(handlers); + ArgumentNullThrowHelper.ThrowIfNull(logger); + ArgumentNullThrowHelper.ThrowIfNull(contextFactory); + ArgumentNullThrowHelper.ThrowIfNull(evaluator); _options = options.Value; _handlers = handlers; @@ -78,10 +61,7 @@ public DefaultAuthorizationService(IAuthorizationPolicyProvider policyProvider, /// public virtual async Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) { - if (requirements == null) - { - throw new ArgumentNullException(nameof(requirements)); - } + ArgumentNullThrowHelper.ThrowIfNull(requirements); var authContext = _contextFactory.CreateContext(requirements, user, resource); var handlers = await _handlers.GetHandlersAsync(authContext).ConfigureAwait(false); @@ -118,10 +98,7 @@ public virtual async Task AuthorizeAsync(ClaimsPrincipal us /// public virtual async Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) { - if (policyName == null) - { - throw new ArgumentNullException(nameof(policyName)); - } + ArgumentNullThrowHelper.ThrowIfNull(policyName); var policy = await _policyProvider.GetPolicyAsync(policyName).ConfigureAwait(false); if (policy == null) diff --git a/src/Security/Authorization/Core/src/Microsoft.AspNetCore.Authorization.csproj b/src/Security/Authorization/Core/src/Microsoft.AspNetCore.Authorization.csproj index 77ce4849404b..c7a3b5c0b7e4 100644 --- a/src/Security/Authorization/Core/src/Microsoft.AspNetCore.Authorization.csproj +++ b/src/Security/Authorization/Core/src/Microsoft.AspNetCore.Authorization.csproj @@ -24,5 +24,10 @@ Microsoft.AspNetCore.Authorization.AuthorizeAttribute - + + + + + + diff --git a/src/Security/Authorization/Core/src/NameAuthorizationRequirement.cs b/src/Security/Authorization/Core/src/NameAuthorizationRequirement.cs index 95caf8ac7d33..563cf5ede0f2 100644 --- a/src/Security/Authorization/Core/src/NameAuthorizationRequirement.cs +++ b/src/Security/Authorization/Core/src/NameAuthorizationRequirement.cs @@ -4,6 +4,7 @@ using System; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization.Infrastructure; @@ -19,10 +20,7 @@ public class NameAuthorizationRequirement : AuthorizationHandlerThe required name that the current user must have. public NameAuthorizationRequirement(string requiredName) { - if (requiredName == null) - { - throw new ArgumentNullException(nameof(requiredName)); - } + ArgumentNullThrowHelper.ThrowIfNull(requiredName); RequiredName = requiredName; } diff --git a/src/Security/Authorization/Core/src/RolesAuthorizationRequirement.cs b/src/Security/Authorization/Core/src/RolesAuthorizationRequirement.cs index 43d953b4311e..d3a78366dbdd 100644 --- a/src/Security/Authorization/Core/src/RolesAuthorizationRequirement.cs +++ b/src/Security/Authorization/Core/src/RolesAuthorizationRequirement.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Authorization.Infrastructure; @@ -20,10 +21,7 @@ public class RolesAuthorizationRequirement : AuthorizationHandlerA collection of allowed roles. public RolesAuthorizationRequirement(IEnumerable allowedRoles) { - if (allowedRoles == null) - { - throw new ArgumentNullException(nameof(allowedRoles)); - } + ArgumentNullThrowHelper.ThrowIfNull(allowedRoles); if (!allowedRoles.Any()) { diff --git a/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs b/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs index 74b23c01f871..4d74e84945e7 100644 --- a/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs +++ b/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs @@ -25,10 +25,7 @@ public static class AuthorizationAppBuilderExtensions /// A reference to after the operation has completed. public static IApplicationBuilder UseAuthorization(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); VerifyServicesRegistered(app); diff --git a/src/Security/Authorization/Policy/src/AuthorizationEndpointConventionBuilderExtensions.cs b/src/Security/Authorization/Policy/src/AuthorizationEndpointConventionBuilderExtensions.cs index 83a19972ffc7..8b45ed1a0aee 100644 --- a/src/Security/Authorization/Policy/src/AuthorizationEndpointConventionBuilderExtensions.cs +++ b/src/Security/Authorization/Policy/src/AuthorizationEndpointConventionBuilderExtensions.cs @@ -41,10 +41,7 @@ public static TBuilder RequireAuthorization(this TBuilder builder, par throw new ArgumentNullException(nameof(builder)); } - if (policyNames == null) - { - throw new ArgumentNullException(nameof(policyNames)); - } + ArgumentNullException.ThrowIfNull(policyNames); return builder.RequireAuthorization(policyNames.Select(n => new AuthorizeAttribute(n)).ToArray()); } @@ -65,10 +62,7 @@ public static TBuilder RequireAuthorization(this TBuilder builder, par throw new ArgumentNullException(nameof(builder)); } - if (authorizeData == null) - { - throw new ArgumentNullException(nameof(authorizeData)); - } + ArgumentNullException.ThrowIfNull(authorizeData); if (authorizeData.Length == 0) { @@ -93,10 +87,7 @@ public static TBuilder RequireAuthorization(this TBuilder builder, Aut throw new ArgumentNullException(nameof(builder)); } - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(policy); RequirePolicyCore(builder, policy); return builder; @@ -117,10 +108,7 @@ public static TBuilder RequireAuthorization(this TBuilder builder, Act throw new ArgumentNullException(nameof(builder)); } - if (configurePolicy == null) - { - throw new ArgumentNullException(nameof(configurePolicy)); - } + ArgumentNullException.ThrowIfNull(configurePolicy); var policyBuilder = new AuthorizationPolicyBuilder(); configurePolicy(policyBuilder); diff --git a/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs b/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs index 2ff13e3779e1..733b10dfb38b 100644 --- a/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs +++ b/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs @@ -81,10 +81,7 @@ public AuthorizationMiddleware(RequestDelegate next, /// The . public async Task Invoke(HttpContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var endpoint = context.GetEndpoint(); if (endpoint != null) diff --git a/src/Security/Authorization/Policy/src/PolicyEvaluator.cs b/src/Security/Authorization/Policy/src/PolicyEvaluator.cs index fd6d7b44a5b8..2799c2765d0e 100644 --- a/src/Security/Authorization/Policy/src/PolicyEvaluator.cs +++ b/src/Security/Authorization/Policy/src/PolicyEvaluator.cs @@ -93,10 +93,7 @@ static AuthenticateResult DefaultAuthenticateResult(HttpContext context) /// returns public virtual async Task AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object? resource) { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } + ArgumentNullException.ThrowIfNull(policy); var result = await _authorization.AuthorizeAsync(context.User, resource, policy); if (result.Succeeded) diff --git a/src/Security/Authorization/Policy/src/PolicyServiceCollectionExtensions.cs b/src/Security/Authorization/Policy/src/PolicyServiceCollectionExtensions.cs index d1cb056419f3..b7c5b8f0a31c 100644 --- a/src/Security/Authorization/Policy/src/PolicyServiceCollectionExtensions.cs +++ b/src/Security/Authorization/Policy/src/PolicyServiceCollectionExtensions.cs @@ -27,10 +27,7 @@ public static AuthorizationBuilder AddAuthorizationBuilder(this IServiceCollecti /// The so that additional calls can be chained. public static IServiceCollection AddAuthorizationPolicyEvaluator(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); services.TryAddTransient(); @@ -45,10 +42,7 @@ public static IServiceCollection AddAuthorizationPolicyEvaluator(this IServiceCo /// The so that additional calls can be chained. public static IServiceCollection AddAuthorization(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddAuthorizationCore(); services.AddAuthorizationPolicyEvaluator(); @@ -64,10 +58,7 @@ public static IServiceCollection AddAuthorization(this IServiceCollection servic /// The so that additional calls can be chained. public static IServiceCollection AddAuthorization(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddAuthorizationCore(configure); services.AddAuthorizationPolicyEvaluator(); diff --git a/src/Security/CookiePolicy/src/CookiePolicyAppBuilderExtensions.cs b/src/Security/CookiePolicy/src/CookiePolicyAppBuilderExtensions.cs index d259129e6f4e..e9a5413e076d 100644 --- a/src/Security/CookiePolicy/src/CookiePolicyAppBuilderExtensions.cs +++ b/src/Security/CookiePolicy/src/CookiePolicyAppBuilderExtensions.cs @@ -18,10 +18,7 @@ public static class CookiePolicyAppBuilderExtensions /// A reference to this instance after the operation has completed. public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } + ArgumentNullException.ThrowIfNull(app); return app.UseMiddleware(); } @@ -34,14 +31,8 @@ public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app) /// A reference to this instance after the operation has completed. public static IApplicationBuilder UseCookiePolicy(this IApplicationBuilder app, CookiePolicyOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(app); + ArgumentNullException.ThrowIfNull(options); return app.UseMiddleware(Options.Create(options)); } diff --git a/src/Security/CookiePolicy/src/CookiePolicyServiceCollectionExtensions.cs b/src/Security/CookiePolicy/src/CookiePolicyServiceCollectionExtensions.cs index af5428c99eac..fdc53805b73a 100644 --- a/src/Security/CookiePolicy/src/CookiePolicyServiceCollectionExtensions.cs +++ b/src/Security/CookiePolicy/src/CookiePolicyServiceCollectionExtensions.cs @@ -18,14 +18,8 @@ public static class CookiePolicyServiceCollectionExtensions /// public static IServiceCollection AddCookiePolicy(this IServiceCollection services, Action configureOptions) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); return services.Configure(configureOptions); } @@ -38,14 +32,8 @@ public static IServiceCollection AddCookiePolicy(this IServiceCollection service /// public static IServiceCollection AddCookiePolicy(this IServiceCollection services, Action configureOptions) where TService : class { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions().Configure(configureOptions); return services; diff --git a/src/Security/CookiePolicy/src/ResponseCookiesWrapper.cs b/src/Security/CookiePolicy/src/ResponseCookiesWrapper.cs index 6fc2f1141d7e..f027dbdb4a0b 100644 --- a/src/Security/CookiePolicy/src/ResponseCookiesWrapper.cs +++ b/src/Security/CookiePolicy/src/ResponseCookiesWrapper.cs @@ -123,10 +123,7 @@ public void Append(string key, string value) public void Append(string key, string value, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (ApplyAppendPolicy(ref key, ref value, options)) { @@ -140,10 +137,7 @@ public void Append(string key, string value, CookieOptions options) public void Append(ReadOnlySpan> keyValuePairs, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); var nonSuppressedValues = new List>(keyValuePairs.Length); @@ -201,10 +195,7 @@ public void Delete(string key) public void Delete(string key, CookieOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); // Assume you can always delete cookies unless directly overridden in the user event. var issueCookie = true; diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/ApplicationDeployerFactory.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/ApplicationDeployerFactory.cs index 31a241aeedfb..ddaa4bd054db 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/ApplicationDeployerFactory.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/ApplicationDeployerFactory.cs @@ -20,7 +20,6 @@ public class IISApplicationDeployerFactory public static ApplicationDeployer Create(DeploymentParameters deploymentParameters, ILoggerFactory loggerFactory) { ArgumentNullException.ThrowIfNull(deploymentParameters); - ArgumentNullException.ThrowIfNull(loggerFactory); switch (deploymentParameters.ServerType) diff --git a/src/Servers/Kestrel/Core/src/Internal/Http/HttpRequestStream.cs b/src/Servers/Kestrel/Core/src/Internal/Http/HttpRequestStream.cs index 7203ae0cc234..0bef2c73622d 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http/HttpRequestStream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http/HttpRequestStream.cs @@ -155,11 +155,7 @@ private async ValueTask ReadAsyncInternal(Memory destination, Cancell public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(destination); - - if (bufferSize <= 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferSize)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(bufferSize); return _pipeReader.CopyToAsync(destination, cancellationToken); } diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/WrappingStream.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/WrappingStream.cs index 37170d1f2280..8dad11145e39 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/WrappingStream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/WrappingStream.cs @@ -15,11 +15,7 @@ public WrappingStream(Stream inner) public void SetInnerStream(Stream inner) { - if (_disposed) - { - throw new ObjectDisposedException(nameof(WrappingStream)); - } - + ObjectDisposedException.ThrowIf(_disposed, this); _inner = inner; } diff --git a/src/Servers/Kestrel/Core/src/Internal/TlsConnectionFeature.cs b/src/Servers/Kestrel/Core/src/Internal/TlsConnectionFeature.cs index c9ce85ee5621..047ca2c04176 100644 --- a/src/Servers/Kestrel/Core/src/Internal/TlsConnectionFeature.cs +++ b/src/Servers/Kestrel/Core/src/Internal/TlsConnectionFeature.cs @@ -28,14 +28,8 @@ internal sealed class TlsConnectionFeature : ITlsConnectionFeature, ITlsApplicat public TlsConnectionFeature(SslStream sslStream, ConnectionContext context) { - if (sslStream is null) - { - throw new ArgumentNullException(nameof(sslStream)); - } - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(sslStream); + ArgumentNullException.ThrowIfNull(context); _sslStream = sslStream; _context = context; diff --git a/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs b/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs index 7ea815e051f6..175b8bed8163 100644 --- a/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs +++ b/src/Servers/Kestrel/Core/src/ListenOptionsHttpsExtensions.cs @@ -144,7 +144,6 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, X509Certi Action configureOptions) { ArgumentNullException.ThrowIfNull(serverCertificate); - ArgumentNullException.ThrowIfNull(configureOptions); return listenOptions.UseHttps(options => @@ -259,10 +258,7 @@ public static ListenOptions UseHttps(this ListenOptions listenOptions, ServerOpt /// The . public static ListenOptions UseHttps(this ListenOptions listenOptions, TlsHandshakeCallbackOptions callbackOptions) { - if (callbackOptions is null) - { - throw new ArgumentNullException(nameof(callbackOptions)); - } + ArgumentNullException.ThrowIfNull(callbackOptions); if (callbackOptions.OnConnection is null) { diff --git a/src/Servers/Kestrel/Transport.Quic/src/QuicTransportFactory.cs b/src/Servers/Kestrel/Transport.Quic/src/QuicTransportFactory.cs index 068ea113f7dc..deb0ed40e823 100644 --- a/src/Servers/Kestrel/Transport.Quic/src/QuicTransportFactory.cs +++ b/src/Servers/Kestrel/Transport.Quic/src/QuicTransportFactory.cs @@ -21,7 +21,6 @@ internal sealed class QuicTransportFactory : IMultiplexedConnectionListenerFacto public QuicTransportFactory(ILoggerFactory loggerFactory, IOptions options) { ArgumentNullException.ThrowIfNull(options); - ArgumentNullException.ThrowIfNull(loggerFactory); var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Server.Kestrel.Transport.Quic"); diff --git a/src/Servers/Kestrel/Transport.Sockets/src/Client/SocketConnectionFactory.cs b/src/Servers/Kestrel/Transport.Sockets/src/Client/SocketConnectionFactory.cs index 852684456f34..c2878723225b 100644 --- a/src/Servers/Kestrel/Transport.Sockets/src/Client/SocketConnectionFactory.cs +++ b/src/Servers/Kestrel/Transport.Sockets/src/Client/SocketConnectionFactory.cs @@ -24,7 +24,6 @@ internal sealed class SocketConnectionFactory : IConnectionFactory, IAsyncDispos public SocketConnectionFactory(IOptions options, ILoggerFactory loggerFactory) { ArgumentNullException.ThrowIfNull(options); - ArgumentNullException.ThrowIfNull(loggerFactory); _options = options.Value; diff --git a/src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionContextFactory.cs b/src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionContextFactory.cs index 74213af32c82..fe1621a2c800 100644 --- a/src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionContextFactory.cs +++ b/src/Servers/Kestrel/Transport.Sockets/src/SocketConnectionContextFactory.cs @@ -31,7 +31,6 @@ public sealed class SocketConnectionContextFactory : IDisposable public SocketConnectionContextFactory(SocketConnectionFactoryOptions options, ILogger logger) { ArgumentNullException.ThrowIfNull(options); - ArgumentNullException.ThrowIfNull(logger); _options = options; diff --git a/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs b/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs index 939b0a8c32fc..16c1efb78aee 100644 --- a/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs +++ b/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs @@ -27,7 +27,6 @@ public SocketTransportFactory( ILoggerFactory loggerFactory) { ArgumentNullException.ThrowIfNull(options); - ArgumentNullException.ThrowIfNull(loggerFactory); _options = options.Value; diff --git a/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs b/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs index 01fb023901fd..2fa999a73fc8 100644 --- a/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs +++ b/src/Servers/Kestrel/samples/WebTransportInteractiveSampleApp/Program.cs @@ -133,7 +133,7 @@ static async Task handleBidirectionalStream(IWebTransportSession session, Connec // write back the data to the stream await outputPipe.WriteAsync(outputMemory); - memory.Span.Fill(0); + memory.Span.Clear(); } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2TestBase.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2TestBase.cs index 904e38992e71..3e980aa0ba1e 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2TestBase.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2TestBase.cs @@ -716,7 +716,7 @@ protected Task SendHeadersWithPaddingAndPriorityAsync(int streamId, IEnumerable< HPackHeaderWriter.BeginEncodeHeaders(_hpackEncoder, GetHeadersEnumerator(headers), payload, out var length); var padding = buffer.Slice(extendedHeaderLength + length, padLength); - padding.Fill(0); + padding.Clear(); frame.PayloadLength = extendedHeaderLength + length + padLength; diff --git a/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/CombinationsWithoutRepetition.cs b/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/CombinationsWithoutRepetition.cs index 49b7698b0ebf..a637bf9deed6 100644 --- a/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/CombinationsWithoutRepetition.cs +++ b/src/Servers/Kestrel/tools/CodeGenerator/HttpUtilities/CombinationsWithoutRepetition.cs @@ -15,10 +15,7 @@ internal sealed class CombinationsWithoutRepetition : IEnumerator public CombinationsWithoutRepetition(T[] nElements, int p) { - if (nElements.Length < p) - { - throw new ArgumentOutOfRangeException(nameof(p)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(p, nElements.Length); _nElements = nElements; _p = p; diff --git a/src/Shared/ApiExplorerTypes/ProducesResponseTypeMetadata.cs b/src/Shared/ApiExplorerTypes/ProducesResponseTypeMetadata.cs index c43df9b7acbf..4f4e0d76243c 100644 --- a/src/Shared/ApiExplorerTypes/ProducesResponseTypeMetadata.cs +++ b/src/Shared/ApiExplorerTypes/ProducesResponseTypeMetadata.cs @@ -45,10 +45,7 @@ public ProducesResponseTypeMetadata(Type type, int statusCode) /// Additional content types supported by the response. public ProducesResponseTypeMetadata(Type type, int statusCode, string contentType, params string[] additionalContentTypes) { - if (contentType == null) - { - throw new ArgumentNullException(nameof(contentType)); - } + ArgumentNullException.ThrowIfNull(contentType); Type = type ?? throw new ArgumentNullException(nameof(type)); StatusCode = statusCode; diff --git a/src/Shared/BrowserTesting/src/BrowserTestOutputLogger.cs b/src/Shared/BrowserTesting/src/BrowserTestOutputLogger.cs index d9e2aa04d732..a38e20fb412d 100644 --- a/src/Shared/BrowserTesting/src/BrowserTestOutputLogger.cs +++ b/src/Shared/BrowserTesting/src/BrowserTestOutputLogger.cs @@ -13,20 +13,14 @@ internal sealed class BrowserTestOutputLogger : ITestOutputHelper public BrowserTestOutputLogger(ILogger logger) { - if (logger is null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } public void WriteLine(string message) { - if (message is null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(message); _logger.LogInformation(message); } diff --git a/src/Shared/Buffers.Testing/CustomMemoryForTest.cs b/src/Shared/Buffers.Testing/CustomMemoryForTest.cs index 4b534091d668..0eca9ca2a86c 100644 --- a/src/Shared/Buffers.Testing/CustomMemoryForTest.cs +++ b/src/Shared/Buffers.Testing/CustomMemoryForTest.cs @@ -25,10 +25,7 @@ public Memory Memory { get { - if (_disposed) - { - throw new ObjectDisposedException(nameof(CustomMemoryForTest)); - } + ObjectDisposedException.ThrowIf(_disposed, this); return new Memory(_array, _offset, _length); } } diff --git a/src/Shared/CallerArgument/CallerArgumentExpressionAttribute.cs b/src/Shared/CallerArgument/CallerArgumentExpressionAttribute.cs new file mode 100644 index 000000000000..bac02b8b5aa6 --- /dev/null +++ b/src/Shared/CallerArgument/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// From https://github.com/dotnet/runtime/blob/5da4a9e919dcee35f831ab69b6e475baaf798875/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs + +namespace System.Runtime.CompilerServices; + +#if !NETCOREAPP3_0_OR_GREATER +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] +internal sealed class CallerArgumentExpressionAttribute : Attribute +{ + public CallerArgumentExpressionAttribute(string parameterName) + { + ParameterName = parameterName; + } + + public string ParameterName { get; } +} +#endif diff --git a/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs b/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs index 462c2f610ec3..182981b78036 100644 --- a/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs +++ b/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs @@ -88,15 +88,8 @@ private static int ParseChunksCount(string? value) /// The reassembled cookie, if any, or null. public string? GetRequestCookie(HttpContext context, string key) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(key); var requestCookies = context.Request.Cookies; var value = requestCookies[key]; @@ -150,20 +143,9 @@ private static int ParseChunksCount(string? value) /// public void AppendResponseCookie(HttpContext context, string key, string? value, CookieOptions options) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(options); var responseCookies = context.Response.Cookies; @@ -225,20 +207,9 @@ public void AppendResponseCookie(HttpContext context, string key, string? value, public void DeleteCookie(HttpContext context, string key, CookieOptions options) #pragma warning restore CA1822 // Mark members as static { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(options); var keys = new List { diff --git a/src/Shared/ClosedGenericMatcher/ClosedGenericMatcher.cs b/src/Shared/ClosedGenericMatcher/ClosedGenericMatcher.cs index 390a77d668fa..7a77dfa3d4cc 100644 --- a/src/Shared/ClosedGenericMatcher/ClosedGenericMatcher.cs +++ b/src/Shared/ClosedGenericMatcher/ClosedGenericMatcher.cs @@ -5,6 +5,7 @@ using System; using System.Reflection; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Internal; @@ -31,15 +32,8 @@ internal static class ClosedGenericMatcher /// public static Type? ExtractGenericInterface(Type queryType, Type interfaceType) { - if (queryType == null) - { - throw new ArgumentNullException(nameof(queryType)); - } - - if (interfaceType == null) - { - throw new ArgumentNullException(nameof(interfaceType)); - } + ArgumentNullThrowHelper.ThrowIfNull(queryType); + ArgumentNullThrowHelper.ThrowIfNull(interfaceType); if (IsGenericInstantiation(queryType, interfaceType)) { diff --git a/src/Shared/Components/PrerenderComponentApplicationStore.cs b/src/Shared/Components/PrerenderComponentApplicationStore.cs index 7edaf5dc14c7..ed56f7f349b9 100644 --- a/src/Shared/Components/PrerenderComponentApplicationStore.cs +++ b/src/Shared/Components/PrerenderComponentApplicationStore.cs @@ -18,10 +18,7 @@ public PrerenderComponentApplicationStore() [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Simple deserialize of primitive types.")] public PrerenderComponentApplicationStore(string existingState) { - if (existingState is null) - { - throw new ArgumentNullException(nameof(existingState)); - } + ArgumentNullException.ThrowIfNull(existingState); DeserializeState(Convert.FromBase64String(existingState)); } diff --git a/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionary.cs b/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionary.cs index 49f4b8869e78..204dd80909ff 100644 --- a/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionary.cs +++ b/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionary.cs @@ -19,15 +19,8 @@ public CopyOnWriteDictionary( IDictionary sourceDictionary, IEqualityComparer comparer) { - if (sourceDictionary == null) - { - throw new ArgumentNullException(nameof(sourceDictionary)); - } - - if (comparer == null) - { - throw new ArgumentNullException(nameof(comparer)); - } + ArgumentNullException.ThrowIfNull(sourceDictionary); + ArgumentNullException.ThrowIfNull(comparer); _sourceDictionary = sourceDictionary; _comparer = comparer; diff --git a/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs b/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs index f664028fc378..c8fc28dccd74 100644 --- a/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs +++ b/src/Shared/CopyOnWriteDictionary/CopyOnWriteDictionaryHolder.cs @@ -16,10 +16,7 @@ internal struct CopyOnWriteDictionaryHolder where TKey : notnull public CopyOnWriteDictionaryHolder(Dictionary source) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); _source = source; _copy = null; diff --git a/src/Shared/Diagnostics/BaseView.cs b/src/Shared/Diagnostics/BaseView.cs index 139420085a31..6514cefb4cf4 100644 --- a/src/Shared/Diagnostics/BaseView.cs +++ b/src/Shared/Diagnostics/BaseView.cs @@ -141,25 +141,10 @@ protected void WriteAttributeTo( string trailer, params AttributeValue[] values) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (leader == null) - { - throw new ArgumentNullException(nameof(leader)); - } - - if (trailer == null) - { - throw new ArgumentNullException(nameof(trailer)); - } + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(leader); + ArgumentNullException.ThrowIfNull(trailer); WriteLiteralTo(writer, leader); foreach (var value in values) diff --git a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs index 829941c76be1..9659f94bac64 100644 --- a/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs +++ b/src/Shared/Dictionary/AdaptiveCapacityDictionary.cs @@ -289,10 +289,7 @@ void ICollection>.CopyTo( KeyValuePair[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if ((uint)arrayIndex > array.Length || array.Length - arrayIndex < this.Count) { @@ -609,10 +606,7 @@ public struct Enumerator : IEnumerator> /// A . public Enumerator(AdaptiveCapacityDictionary dictionary) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } + ArgumentNullException.ThrowIfNull(dictionary); _dictionary = dictionary; diff --git a/src/Shared/E2ETesting/WebDriverExtensions.cs b/src/Shared/E2ETesting/WebDriverExtensions.cs index e3e25ee45bf1..50cbefdc9e3a 100644 --- a/src/Shared/E2ETesting/WebDriverExtensions.cs +++ b/src/Shared/E2ETesting/WebDriverExtensions.cs @@ -11,10 +11,7 @@ public static class WebDriverExtensions { public static IReadOnlyList GetBrowserLogs(this IWebDriver driver, LogLevel level) { - if (driver is null) - { - throw new ArgumentNullException(nameof(driver)); - } + ArgumentNullException.ThrowIfNull(driver); // Fail-fast if any errors were logged to the console. var log = driver.Manage().Logs.GetLog(LogType.Browser); diff --git a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs index b7b4a52afa70..2d1254289f6f 100644 --- a/src/Shared/HttpSys/NativeInterop/SocketAddress.cs +++ b/src/Shared/HttpSys/NativeInterop/SocketAddress.cs @@ -45,13 +45,7 @@ internal sealed class SocketAddress /// public SocketAddress(AddressFamily family, int size) { - if (size < WriteableOffset) - { - // it doesn't make sense to create a socket address with less tha - // 2 bytes, that's where we store the address family. - - throw new ArgumentOutOfRangeException(nameof(size)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(size, WriteableOffset); _size = size; _buffer = new byte[((size / IntPtr.Size) + 2) * IntPtr.Size]; // sizeof DWORD diff --git a/src/Shared/NonCapturingTimer/NonCapturingTimer.cs b/src/Shared/NonCapturingTimer/NonCapturingTimer.cs index 7d4482066f1c..711f93677219 100644 --- a/src/Shared/NonCapturingTimer/NonCapturingTimer.cs +++ b/src/Shared/NonCapturingTimer/NonCapturingTimer.cs @@ -4,6 +4,7 @@ using System; using System.Threading; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Internal; @@ -14,10 +15,7 @@ internal static class NonCapturingTimer { public static Timer Create(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullThrowHelper.ThrowIfNull(callback); // Don't capture the current ExecutionContext and its AsyncLocals onto the timer bool restoreFlow = false; diff --git a/src/Shared/ObjectMethodExecutor/ObjectMethodExecutor.cs b/src/Shared/ObjectMethodExecutor/ObjectMethodExecutor.cs index 8767cc2b4b7c..8de064da2216 100644 --- a/src/Shared/ObjectMethodExecutor/ObjectMethodExecutor.cs +++ b/src/Shared/ObjectMethodExecutor/ObjectMethodExecutor.cs @@ -30,10 +30,7 @@ internal sealed class ObjectMethodExecutor private ObjectMethodExecutor(MethodInfo methodInfo, TypeInfo targetTypeInfo, object?[]? parameterDefaultValues) { - if (methodInfo == null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(methodInfo); MethodInfo = methodInfo; MethodParameters = methodInfo.GetParameters(); @@ -84,10 +81,7 @@ public static ObjectMethodExecutor Create(MethodInfo methodInfo, TypeInfo target public static ObjectMethodExecutor Create(MethodInfo methodInfo, TypeInfo targetTypeInfo, object?[] parameterDefaultValues) { - if (parameterDefaultValues == null) - { - throw new ArgumentNullException(nameof(parameterDefaultValues)); - } + ArgumentNullException.ThrowIfNull(parameterDefaultValues); return new ObjectMethodExecutor(methodInfo, targetTypeInfo, parameterDefaultValues); } diff --git a/src/Shared/PooledArrayBufferWriter.cs b/src/Shared/PooledArrayBufferWriter.cs index a410ed3bc9d6..9fad4a0a404a 100644 --- a/src/Shared/PooledArrayBufferWriter.cs +++ b/src/Shared/PooledArrayBufferWriter.cs @@ -22,10 +22,7 @@ public PooledArrayBufferWriter() public PooledArrayBufferWriter(int initialCapacity) { - if (initialCapacity <= 0) - { - throw new ArgumentOutOfRangeException(nameof(initialCapacity)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(initialCapacity); _rentedBuffer = ArrayPool.Shared.Rent(initialCapacity); _index = 0; @@ -116,10 +113,7 @@ public void Advance(int count) { CheckIfDisposed(); - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeException.ThrowIfNegative(count); if (_index > _rentedBuffer.Length - count) { @@ -149,10 +143,7 @@ private void CheckAndResizeBuffer(int sizeHint) { Debug.Assert(_rentedBuffer != null); - if (sizeHint < 0) - { - throw new ArgumentOutOfRangeException(nameof(sizeHint)); - } + ArgumentOutOfRangeException.ThrowIfNegative(sizeHint); if (sizeHint == 0) { diff --git a/src/Shared/PropertyActivator/PropertyActivator.cs b/src/Shared/PropertyActivator/PropertyActivator.cs index c7c462d51a76..df179a505a58 100644 --- a/src/Shared/PropertyActivator/PropertyActivator.cs +++ b/src/Shared/PropertyActivator/PropertyActivator.cs @@ -27,10 +27,7 @@ public PropertyActivator( public object Activate(object instance, TContext context) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } + ArgumentNullException.ThrowIfNull(instance); var value = _valueAccessor(context); _fastPropertySetter(instance, value); @@ -42,20 +39,9 @@ public static PropertyActivator[] GetPropertiesToActivate( Type activateAttributeType, Func> createActivateInfo) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (activateAttributeType == null) - { - throw new ArgumentNullException(nameof(activateAttributeType)); - } - - if (createActivateInfo == null) - { - throw new ArgumentNullException(nameof(createActivateInfo)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(activateAttributeType); + ArgumentNullException.ThrowIfNull(createActivateInfo); return GetPropertiesToActivate(type, activateAttributeType, createActivateInfo, includeNonPublic: false); } @@ -66,20 +52,9 @@ public static PropertyActivator[] GetPropertiesToActivate( Func> createActivateInfo, bool includeNonPublic) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (activateAttributeType == null) - { - throw new ArgumentNullException(nameof(activateAttributeType)); - } - - if (createActivateInfo == null) - { - throw new ArgumentNullException(nameof(createActivateInfo)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(activateAttributeType); + ArgumentNullException.ThrowIfNull(createActivateInfo); var properties = type.GetRuntimeProperties() .Where((property) => diff --git a/src/Shared/RazorViews/BaseView.cs b/src/Shared/RazorViews/BaseView.cs index 1572ffdbbc48..d2fca2e22c00 100644 --- a/src/Shared/RazorViews/BaseView.cs +++ b/src/Shared/RazorViews/BaseView.cs @@ -98,10 +98,7 @@ public async Task ExecuteAsync(HttpContext context) protected virtual void PushWriter(TextWriter writer) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); _textWriterStack.Push(Output); Output = writer; @@ -182,20 +179,9 @@ protected void WriteAttribute( string trailer, params AttributeValue[] values) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (leader == null) - { - throw new ArgumentNullException(nameof(leader)); - } - - if (trailer == null) - { - throw new ArgumentNullException(nameof(trailer)); - } + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(leader); + ArgumentNullException.ThrowIfNull(trailer); WriteLiteral(leader); foreach (var value in values) diff --git a/src/Shared/RoutingMetadata/AcceptsMetadata.cs b/src/Shared/RoutingMetadata/AcceptsMetadata.cs index 5223c8e1c123..23d505d6f991 100644 --- a/src/Shared/RoutingMetadata/AcceptsMetadata.cs +++ b/src/Shared/RoutingMetadata/AcceptsMetadata.cs @@ -18,10 +18,7 @@ internal sealed class AcceptsMetadata : IAcceptsMetadata /// public AcceptsMetadata(string[] contentTypes) { - if (contentTypes == null) - { - throw new ArgumentNullException(nameof(contentTypes)); - } + ArgumentNullException.ThrowIfNull(contentTypes); ContentTypes = contentTypes; } @@ -31,24 +28,21 @@ public AcceptsMetadata(string[] contentTypes) /// public AcceptsMetadata(Type? type, bool isOptional, string[] contentTypes) { - RequestType = type ?? throw new ArgumentNullException(nameof(type)); - - if (contentTypes == null) - { - throw new ArgumentNullException(nameof(contentTypes)); - } + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(contentTypes); + RequestType = type; ContentTypes = contentTypes; IsOptional = isOptional; } /// - /// Gets the supported request content types. + /// Gets the supported request content types. /// public IReadOnlyList ContentTypes { get; } /// - /// Gets the type being read from the request. + /// Gets the type being read from the request. /// public Type? RequestType { get; } diff --git a/src/Shared/Shared.slnf b/src/Shared/Shared.slnf index 22f958684e47..e64dfa8b29cb 100644 --- a/src/Shared/Shared.slnf +++ b/src/Shared/Shared.slnf @@ -2,8 +2,17 @@ "solution": { "path": "..\\..\\AspNetCore.sln", "projects": [ + "src\\Extensions\\Features\\src\\Microsoft.Extensions.Features.csproj", + "src\\Http\\Headers\\src\\Microsoft.Net.Http.Headers.csproj", + "src\\Http\\Http.Abstractions\\src\\Microsoft.AspNetCore.Http.Abstractions.csproj", + "src\\Http\\Http.Features\\src\\Microsoft.AspNetCore.Http.Features.csproj", + "src\\Http\\Http\\src\\Microsoft.AspNetCore.Http.csproj", + "src\\Http\\WebUtilities\\src\\Microsoft.AspNetCore.WebUtilities.csproj", + "src\\ObjectPool\\src\\Microsoft.Extensions.ObjectPool.csproj", + "src\\Servers\\Connections.Abstractions\\src\\Microsoft.AspNetCore.Connections.Abstractions.csproj", "src\\Shared\\BrowserTesting\\src\\Microsoft.AspNetCore.BrowserTesting.csproj", - "src\\Shared\\test\\Shared.Tests\\Microsoft.AspNetCore.Shared.Tests.csproj" + "src\\Shared\\test\\Shared.Tests\\Microsoft.AspNetCore.Shared.Tests.csproj", + "src\\Testing\\src\\Microsoft.AspNetCore.Testing.csproj" ] } } \ No newline at end of file diff --git a/src/Shared/StaticWebAssets/ManifestStaticWebAssetFileProvider.cs b/src/Shared/StaticWebAssets/ManifestStaticWebAssetFileProvider.cs index d1d5f2f4dcf2..5c3617e789fb 100644 --- a/src/Shared/StaticWebAssets/ManifestStaticWebAssetFileProvider.cs +++ b/src/Shared/StaticWebAssets/ManifestStaticWebAssetFileProvider.cs @@ -39,10 +39,7 @@ public ManifestStaticWebAssetFileProvider(StaticWebAssetManifest manifest, Func< public IDirectoryContents GetDirectoryContents(string subpath) { - if (subpath == null) - { - throw new ArgumentNullException(nameof(subpath)); - } + ArgumentNullException.ThrowIfNull(subpath); var segments = Normalize(subpath).Split('/', StringSplitOptions.RemoveEmptyEntries); var candidate = _root; @@ -156,10 +153,7 @@ private static string Normalize(string path) public IFileInfo GetFileInfo(string subpath) { - if (subpath == null) - { - throw new ArgumentNullException(nameof(subpath)); - } + ArgumentNullException.ThrowIfNull(subpath); var segments = subpath.Split('/', StringSplitOptions.RemoveEmptyEntries); StaticWebAssetNode? candidate = _root; diff --git a/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs b/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs new file mode 100644 index 000000000000..c899b8511722 --- /dev/null +++ b/src/Shared/ThrowHelpers/ArgumentNullThrowHelper.cs @@ -0,0 +1,34 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.AspNetCore.Shared; + +#nullable enable + +internal static partial class ArgumentNullThrowHelper +{ + /// Throws an if is null. + /// The reference type argument to validate as non-null. + /// The name of the parameter with which corresponds. + public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) + { +#if !NET7_0_OR_GREATER + if (argument is null) + { + Throw(paramName); + } +#else + ArgumentNullException.ThrowIfNull(argument, paramName); +#endif + } + +#if !NET7_0_OR_GREATER + [DoesNotReturn] + internal static void Throw(string? paramName) => + throw new ArgumentNullException(paramName); +#endif +} diff --git a/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs b/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs new file mode 100644 index 000000000000..f66ae7d6c410 --- /dev/null +++ b/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs @@ -0,0 +1,168 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.AspNetCore.Shared; + +internal static partial class ArgumentOutOfRangeThrowHelper +{ +#if !NET7_0_OR_GREATER + [DoesNotReturn] + private static void ThrowZero(string? paramName, T value) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{paramName}' must be a non-zero value."); + } + + [DoesNotReturn] + private static void ThrowNegative(string? paramName, T value) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{paramName}' must be a non-negative value."); + } + + [DoesNotReturn] + private static void ThrowNegativeOrZero(string? paramName, T value) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{paramName}' must be a non-negative and non-zero value."); + } + + [DoesNotReturn] + private static void ThrowGreater(string? paramName, T value, T other) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{paramName}' must be less than or equal to '{other}'."); + } + + [DoesNotReturn] + private static void ThrowGreaterEqual(string? paramName, T value, T other) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{value}' must be less than '{other}'."); + } + + [DoesNotReturn] + private static void ThrowLess(string? paramName, T value, T other) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{value}' must be greater than or equal to '{other}'."); + } + + [DoesNotReturn] + private static void ThrowLessEqual(string? paramName, T value, T other) + { + throw new ArgumentOutOfRangeException(paramName, value, $"'{value}' must be greater than '{other}'."); + } +#endif + + /// Throws an if is zero. + /// The argument to validate as non-zero. + /// The name of the parameter with which corresponds. + public static void ThrowIfZero(int value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { +#if !NET7_0_OR_GREATER + if (value == 0) + { + ThrowZero(paramName, value); + } +#else + ArgumentOutOfRangeException.ThrowIfZero(value, paramName); +#endif + } + + /// Throws an if is negative. + /// The argument to validate as non-negative. + /// The name of the parameter with which corresponds. + public static void ThrowIfNegative(int value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { +#if !NET7_0_OR_GREATER + if (value < 0) + { + ThrowNegative(paramName, value); + } +#else + ArgumentOutOfRangeException.ThrowIfNegative(value, paramName); +#endif + } + + /// Throws an if is negative or zero. + /// The argument to validate as non-zero or non-negative. + /// The name of the parameter with which corresponds. + public static void ThrowIfNegativeOrZero(int value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { +#if !NET7_0_OR_GREATER + if (value <= 0) + { + ThrowNegativeOrZero(paramName, value); + } +#else + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value, paramName); +#endif + } + + /// Throws an if is greater than . + /// The argument to validate as less or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static void ThrowIfGreaterThan(T value, T other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + where T : IComparable + { +#if !NET7_0_OR_GREATER + if (value.CompareTo(other) > 0) + { + ThrowGreater(paramName, value, other); + } +#else + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, other, paramName); +#endif + } + + /// Throws an if is greater than or equal . + /// The argument to validate as less than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static void ThrowIfGreaterThanOrEqual(T value, T other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + where T : IComparable + { +#if !NET7_0_OR_GREATER + if (value.CompareTo(other) >= 0) + { + ThrowGreaterEqual(paramName, value, other); + } +#else + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(value, other, paramName); +#endif + } + + /// Throws an if is less than . + /// The argument to validate as greatar than or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static void ThrowIfLessThan(T value, T other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + where T : IComparable + { +#if !NET7_0_OR_GREATER + if (value.CompareTo(other) < 0) + { + ThrowLess(paramName, value, other); + } +#else + ArgumentOutOfRangeException.ThrowIfLessThan(value, other, paramName); +#endif + } + + /// Throws an if is less than or equal . + /// The argument to validate as greatar than than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + public static void ThrowIfLessThanOrEqual(T value, T other, [CallerArgumentExpression(nameof(value))] string? paramName = null) + where T : IComparable + { +#if !NET7_0_OR_GREATER + if (value.CompareTo(other) <= 0) + { + ThrowLessEqual(paramName, value, other); + } +#else + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(value, other, paramName); +#endif + } +} diff --git a/src/Shared/WebEncoders/WebEncoders.cs b/src/Shared/WebEncoders/WebEncoders.cs index 9510c7247a77..4dc85bb8a227 100644 --- a/src/Shared/WebEncoders/WebEncoders.cs +++ b/src/Shared/WebEncoders/WebEncoders.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.WebEncoders.Sources; #if WebEncoders_In_WebUtilities @@ -37,10 +38,7 @@ static class WebEncoders /// public static byte[] Base64UrlDecode(string input) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); return Base64UrlDecode(input, offset: 0, count: input.Length); } @@ -58,10 +56,7 @@ public static byte[] Base64UrlDecode(string input) /// public static byte[] Base64UrlDecode(string input, int offset, int count) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); ValidateParameters(input.Length, nameof(input), offset, count); @@ -98,20 +93,11 @@ public static byte[] Base64UrlDecode(string input, int offset, int count) /// public static byte[] Base64UrlDecode(string input, int offset, char[] buffer, int bufferOffset, int count) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); + ArgumentNullThrowHelper.ThrowIfNull(buffer); ValidateParameters(input.Length, nameof(input), offset, count); - if (bufferOffset < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferOffset)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(bufferOffset); if (count == 0) { @@ -176,10 +162,7 @@ public static byte[] Base64UrlDecode(string input, int offset, char[] buffer, in /// public static int GetArraySizeRequiredToDecode(int count) { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(count); if (count == 0) { @@ -198,10 +181,7 @@ public static int GetArraySizeRequiredToDecode(int count) /// The base64url-encoded form of . public static string Base64UrlEncode(byte[] input) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); return Base64UrlEncode(input, offset: 0, count: input.Length); } @@ -215,10 +195,7 @@ public static string Base64UrlEncode(byte[] input) /// The base64url-encoded form of . public static string Base64UrlEncode(byte[] input, int offset, int count) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); ValidateParameters(input.Length, nameof(input), offset, count); @@ -258,20 +235,11 @@ public static string Base64UrlEncode(byte[] input, int offset, int count) /// public static int Base64UrlEncode(byte[] input, int offset, char[] output, int outputOffset, int count) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + ArgumentNullThrowHelper.ThrowIfNull(input); + ArgumentNullThrowHelper.ThrowIfNull(output); ValidateParameters(input.Length, nameof(input), offset, count); - if (outputOffset < 0) - { - throw new ArgumentOutOfRangeException(nameof(outputOffset)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(outputOffset); var arraySizeRequired = GetArraySizeRequiredToEncode(count); if (output.Length - outputOffset < arraySizeRequired) @@ -428,14 +396,8 @@ private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength) private static void ValidateParameters(int bufferLength, string inputName, int offset, int count) { - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(offset); + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(count); if (bufferLength - offset < count) { throw new ArgumentException( diff --git a/src/Shared/test/Shared.Tests/Microsoft.AspNetCore.Shared.Tests.csproj b/src/Shared/test/Shared.Tests/Microsoft.AspNetCore.Shared.Tests.csproj index cdf361b60d88..665d9d371927 100644 --- a/src/Shared/test/Shared.Tests/Microsoft.AspNetCore.Shared.Tests.csproj +++ b/src/Shared/test/Shared.Tests/Microsoft.AspNetCore.Shared.Tests.csproj @@ -32,6 +32,8 @@ + + diff --git a/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj b/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj index 0fe14fda5c80..d65aa9f8f44b 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj +++ b/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj @@ -15,6 +15,8 @@ + + diff --git a/src/SignalR/common/Http.Connections/src/HttpConnectionDispatcherOptions.cs b/src/SignalR/common/Http.Connections/src/HttpConnectionDispatcherOptions.cs index d2f9f8419f2f..9622425f7877 100644 --- a/src/SignalR/common/Http.Connections/src/HttpConnectionDispatcherOptions.cs +++ b/src/SignalR/common/Http.Connections/src/HttpConnectionDispatcherOptions.cs @@ -67,10 +67,7 @@ public long TransportMaxBufferSize get => _transportMaxBufferSize; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _transportMaxBufferSize = value; } @@ -87,10 +84,7 @@ public long ApplicationMaxBufferSize get => _applicationMaxBufferSize; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeException.ThrowIfNegative(value); _applicationMaxBufferSize = value; } diff --git a/src/SignalR/common/Http.Connections/src/Internal/Transports/WebSocketsServerTransport.cs b/src/SignalR/common/Http.Connections/src/Internal/Transports/WebSocketsServerTransport.cs index 67de725c6255..3d473aa095b9 100644 --- a/src/SignalR/common/Http.Connections/src/Internal/Transports/WebSocketsServerTransport.cs +++ b/src/SignalR/common/Http.Connections/src/Internal/Transports/WebSocketsServerTransport.cs @@ -19,20 +19,9 @@ internal sealed partial class WebSocketsServerTransport : IHttpTransport public WebSocketsServerTransport(WebSocketOptions options, IDuplexPipe application, HttpConnectionContext connection, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (application == null) - { - throw new ArgumentNullException(nameof(application)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(application); + ArgumentNullException.ThrowIfNull(loggerFactory); _options = options; _application = application; diff --git a/src/SignalR/common/Http.Connections/src/Microsoft.AspNetCore.Http.Connections.csproj b/src/SignalR/common/Http.Connections/src/Microsoft.AspNetCore.Http.Connections.csproj index cd4ee8fd2d68..b0310d4225e2 100644 --- a/src/SignalR/common/Http.Connections/src/Microsoft.AspNetCore.Http.Connections.csproj +++ b/src/SignalR/common/Http.Connections/src/Microsoft.AspNetCore.Http.Connections.csproj @@ -24,6 +24,9 @@ + + + diff --git a/src/SignalR/common/testassets/Tests.Utils/HubConnectionBuilderTestExtensions.cs b/src/SignalR/common/testassets/Tests.Utils/HubConnectionBuilderTestExtensions.cs index 9e73b5958993..0bd32eb4fa9e 100644 --- a/src/SignalR/common/testassets/Tests.Utils/HubConnectionBuilderTestExtensions.cs +++ b/src/SignalR/common/testassets/Tests.Utils/HubConnectionBuilderTestExtensions.cs @@ -12,10 +12,7 @@ public static class HubConnectionBuilderTestExtensions // https://github.com/aspnet/Logging/blob/671af986ec3b46dc81e28e4a6c37a9d0ee283c65/src/Microsoft.Extensions.Logging.Testing/AssemblyTestLog.cs#L130 public static IHubConnectionBuilder WithLoggerFactory(this IHubConnectionBuilder hubConnectionBuilder, ILoggerFactory loggerFactory) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullException.ThrowIfNull(loggerFactory); hubConnectionBuilder.Services.AddSingleton(loggerFactory); return hubConnectionBuilder; diff --git a/src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs b/src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs index 230af87fc33e..f2bb90e5b9ef 100644 --- a/src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs +++ b/src/SignalR/server/Core/src/DefaultHubLifetimeManager.cs @@ -34,15 +34,8 @@ public DefaultHubLifetimeManager(ILogger> logger /// public override Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } - - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(connectionId); + ArgumentNullException.ThrowIfNull(groupName); var connection = _connections[connectionId]; if (connection == null) @@ -63,15 +56,8 @@ public override Task AddToGroupAsync(string connectionId, string groupName, Canc /// public override Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } - - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(connectionId); + ArgumentNullException.ThrowIfNull(groupName); var connection = _connections[connectionId]; if (connection == null) @@ -176,10 +162,7 @@ private static void SendToGroupConnections(string methodName, object?[] args, Co /// public override Task SendConnectionAsync(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } + ArgumentNullException.ThrowIfNull(connectionId); var connection = _connections[connectionId]; @@ -198,10 +181,7 @@ public override Task SendConnectionAsync(string connectionId, string methodName, /// public override Task SendGroupAsync(string groupName, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(groupName); var group = _groups[groupName]; if (group != null) @@ -253,10 +233,7 @@ public override Task SendGroupsAsync(IReadOnlyList groupNames, string me /// public override Task SendGroupExceptAsync(string groupName, string methodName, object?[] args, IReadOnlyList excludedConnectionIds, CancellationToken cancellationToken = default) { - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(groupName); var group = _groups[groupName]; if (group != null) @@ -328,10 +305,7 @@ public override Task SendUsersAsync(IReadOnlyList userIds, string method /// public override async Task InvokeConnectionAsync(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } + ArgumentNullException.ThrowIfNull(connectionId); var connection = _connections[connectionId]; diff --git a/src/SignalR/server/Core/src/Hub.cs b/src/SignalR/server/Core/src/Hub.cs index 7b580ca0d42f..acf89fffc961 100644 --- a/src/SignalR/server/Core/src/Hub.cs +++ b/src/SignalR/server/Core/src/Hub.cs @@ -106,9 +106,6 @@ public void Dispose() private void CheckDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedException.ThrowIf(_disposed, this); } } diff --git a/src/SignalR/server/Core/src/HubOptions.cs b/src/SignalR/server/Core/src/HubOptions.cs index 7fd11b0cfcb1..3a4e0883f884 100644 --- a/src/SignalR/server/Core/src/HubOptions.cs +++ b/src/SignalR/server/Core/src/HubOptions.cs @@ -65,10 +65,7 @@ public int MaximumParallelInvocationsPerClient get => _maximumParallelInvocationsPerClient; set { - if (value < 1) - { - throw new ArgumentOutOfRangeException(nameof(MaximumParallelInvocationsPerClient)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); _maximumParallelInvocationsPerClient = value; } diff --git a/src/SignalR/server/Core/src/Internal/DefaultHubActivator.cs b/src/SignalR/server/Core/src/Internal/DefaultHubActivator.cs index 018854227ddf..0d9b91178f0c 100644 --- a/src/SignalR/server/Core/src/Internal/DefaultHubActivator.cs +++ b/src/SignalR/server/Core/src/Internal/DefaultHubActivator.cs @@ -35,10 +35,7 @@ public THub Create() public void Release(THub hub) { - if (hub == null) - { - throw new ArgumentNullException(nameof(hub)); - } + ArgumentNullException.ThrowIfNull(hub); Debug.Assert(_created.HasValue, "hubs must be released with the hub activator they were created"); diff --git a/src/SignalR/server/Core/src/Microsoft.AspNetCore.SignalR.Core.csproj b/src/SignalR/server/Core/src/Microsoft.AspNetCore.SignalR.Core.csproj index fd607f3d832b..741fa83d85ed 100644 --- a/src/SignalR/server/Core/src/Microsoft.AspNetCore.SignalR.Core.csproj +++ b/src/SignalR/server/Core/src/Microsoft.AspNetCore.SignalR.Core.csproj @@ -19,6 +19,8 @@ + + diff --git a/src/SignalR/server/SignalR/src/GetHttpContextExtensions.cs b/src/SignalR/server/SignalR/src/GetHttpContextExtensions.cs index dce405c10577..fa18bc3e4043 100644 --- a/src/SignalR/server/SignalR/src/GetHttpContextExtensions.cs +++ b/src/SignalR/server/SignalR/src/GetHttpContextExtensions.cs @@ -18,10 +18,7 @@ public static class GetHttpContextExtensions /// The for the connection, or null if the connection is not associated with an HTTP request. public static HttpContext? GetHttpContext(this HubCallerContext connection) { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } + ArgumentNullException.ThrowIfNull(connection); return connection.Features.Get()?.HttpContext; } @@ -32,10 +29,7 @@ public static class GetHttpContextExtensions /// The for the connection, or null if the connection is not associated with an HTTP request. public static HttpContext? GetHttpContext(this HubConnectionContext connection) { - if (connection == null) - { - throw new ArgumentNullException(nameof(connection)); - } + ArgumentNullException.ThrowIfNull(connection); return connection.Features.Get()?.HttpContext; } } diff --git a/src/SignalR/server/SignalR/src/SignalRDependencyInjectionExtensions.cs b/src/SignalR/server/SignalR/src/SignalRDependencyInjectionExtensions.cs index 2d3d6979438c..9b2eded595d6 100644 --- a/src/SignalR/server/SignalR/src/SignalRDependencyInjectionExtensions.cs +++ b/src/SignalR/server/SignalR/src/SignalRDependencyInjectionExtensions.cs @@ -22,10 +22,7 @@ public static class SignalRDependencyInjectionExtensions /// The same instance of the for chaining. public static ISignalRServerBuilder AddHubOptions(this ISignalRServerBuilder signalrBuilder, Action> configure) where THub : Hub { - if (signalrBuilder == null) - { - throw new ArgumentNullException(nameof(signalrBuilder)); - } + ArgumentNullException.ThrowIfNull(signalrBuilder); signalrBuilder.Services.AddSingleton>, HubOptionsSetup>(); signalrBuilder.Services.Configure(configure); @@ -39,10 +36,7 @@ public static ISignalRServerBuilder AddHubOptions(this ISignalRServerBuild /// An that can be used to further configure the SignalR services. public static ISignalRServerBuilder AddSignalR(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddConnections(); // Disable the WebSocket keep alive since SignalR has it's own @@ -60,10 +54,7 @@ public static ISignalRServerBuilder AddSignalR(this IServiceCollection services) /// An that can be used to further configure the SignalR services. public static ISignalRServerBuilder AddSignalR(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var signalrBuilder = services.AddSignalR(); // Setup users settings after we've setup ours diff --git a/src/SignalR/server/StackExchangeRedis/src/Microsoft.AspNetCore.SignalR.StackExchangeRedis.csproj b/src/SignalR/server/StackExchangeRedis/src/Microsoft.AspNetCore.SignalR.StackExchangeRedis.csproj index e3ed270e72ef..deda497d1ec2 100644 --- a/src/SignalR/server/StackExchangeRedis/src/Microsoft.AspNetCore.SignalR.StackExchangeRedis.csproj +++ b/src/SignalR/server/StackExchangeRedis/src/Microsoft.AspNetCore.SignalR.StackExchangeRedis.csproj @@ -12,6 +12,8 @@ + + diff --git a/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs b/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs index 111e2520a7cd..9d79a3ec2f99 100644 --- a/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs +++ b/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs @@ -165,10 +165,7 @@ public override Task SendAllExceptAsync(string methodName, object?[] args, IRead /// public override Task SendConnectionAsync(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } + ArgumentNullException.ThrowIfNull(connectionId); // If the connection is local we can skip sending the message through the bus since we require sticky connections. // This also saves serializing and deserializing the message! @@ -185,10 +182,7 @@ public override Task SendConnectionAsync(string connectionId, string methodName, /// public override Task SendGroupAsync(string groupName, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(groupName); var message = _protocol.WriteInvocation(methodName, args); return PublishAsync(_channels.Group(groupName), message); @@ -197,10 +191,7 @@ public override Task SendGroupAsync(string groupName, string methodName, object? /// public override Task SendGroupExceptAsync(string groupName, string methodName, object?[] args, IReadOnlyList excludedConnectionIds, CancellationToken cancellationToken = default) { - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(groupName); var message = _protocol.WriteInvocation(methodName, args, excludedConnectionIds: excludedConnectionIds); return PublishAsync(_channels.Group(groupName), message); @@ -216,15 +207,8 @@ public override Task SendUserAsync(string userId, string methodName, object?[] a /// public override Task AddToGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } - - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(connectionId); + ArgumentNullException.ThrowIfNull(groupName); var connection = _connections[connectionId]; if (connection != null) @@ -239,15 +223,8 @@ public override Task AddToGroupAsync(string connectionId, string groupName, Canc /// public override Task RemoveFromGroupAsync(string connectionId, string groupName, CancellationToken cancellationToken = default) { - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } - - if (groupName == null) - { - throw new ArgumentNullException(nameof(groupName)); - } + ArgumentNullException.ThrowIfNull(connectionId); + ArgumentNullException.ThrowIfNull(groupName); var connection = _connections[connectionId]; if (connection != null) @@ -262,10 +239,7 @@ public override Task RemoveFromGroupAsync(string connectionId, string groupName, /// public override Task SendConnectionsAsync(IReadOnlyList connectionIds, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (connectionIds == null) - { - throw new ArgumentNullException(nameof(connectionIds)); - } + ArgumentNullException.ThrowIfNull(connectionIds); var publishTasks = new List(connectionIds.Count); var payload = _protocol.WriteInvocation(methodName, args); @@ -281,10 +255,7 @@ public override Task SendConnectionsAsync(IReadOnlyList connectionIds, s /// public override Task SendGroupsAsync(IReadOnlyList groupNames, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (groupNames == null) - { - throw new ArgumentNullException(nameof(groupNames)); - } + ArgumentNullException.ThrowIfNull(groupNames); var publishTasks = new List(groupNames.Count); var payload = _protocol.WriteInvocation(methodName, args); @@ -408,10 +379,7 @@ public void Dispose() public override async Task InvokeConnectionAsync(string connectionId, string methodName, object?[] args, CancellationToken cancellationToken) { // send thing - if (connectionId == null) - { - throw new ArgumentNullException(nameof(connectionId)); - } + ArgumentNullException.ThrowIfNull(connectionId); var connection = _connections[connectionId]; diff --git a/src/SignalR/server/StackExchangeRedis/test/RedisEndToEnd.cs b/src/SignalR/server/StackExchangeRedis/test/RedisEndToEnd.cs index db4312874c74..e0e626f3b23b 100644 --- a/src/SignalR/server/StackExchangeRedis/test/RedisEndToEnd.cs +++ b/src/SignalR/server/StackExchangeRedis/test/RedisEndToEnd.cs @@ -29,10 +29,7 @@ public class RedisEndToEndTests : VerifiableLoggedTest public RedisEndToEndTests(RedisServerFixture serverFixture) { - if (serverFixture == null) - { - throw new ArgumentNullException(nameof(serverFixture)); - } + ArgumentNullException.ThrowIfNull(serverFixture); _serverFixture = serverFixture; } diff --git a/src/Testing/src/Logging/LogValuesAssert.cs b/src/Testing/src/Logging/LogValuesAssert.cs index e60f5777dd34..55c873148207 100644 --- a/src/Testing/src/Logging/LogValuesAssert.cs +++ b/src/Testing/src/Logging/LogValuesAssert.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Microsoft.AspNetCore.Shared; using Xunit.Sdk; namespace Microsoft.Extensions.Logging.Testing; @@ -34,15 +35,8 @@ public static void Contains( IEnumerable> expectedValues, IEnumerable> actualValues) { - if (expectedValues == null) - { - throw new ArgumentNullException(nameof(expectedValues)); - } - - if (actualValues == null) - { - throw new ArgumentNullException(nameof(actualValues)); - } + ArgumentNullThrowHelper.ThrowIfNull(expectedValues); + ArgumentNullThrowHelper.ThrowIfNull(actualValues); var comparer = new LogValueComparer(); diff --git a/src/Testing/src/Microsoft.AspNetCore.Testing.csproj b/src/Testing/src/Microsoft.AspNetCore.Testing.csproj index 961b18b849d6..12180a437d92 100644 --- a/src/Testing/src/Microsoft.AspNetCore.Testing.csproj +++ b/src/Testing/src/Microsoft.AspNetCore.Testing.csproj @@ -3,7 +3,7 @@ Various helpers for writing tests that use ASP.NET Core. $(DefaultNetCoreTargetFramework);$(DefaultNetFxTargetFramework);netstandard2.0 - $(DefineConstants);AspNetCoreTesting + $(DefineConstants);INTERNAL_NULLABLE_ATTRIBUTES;AspNetCoreTesting $(NoWarn);CS1591 true @@ -60,6 +60,12 @@ contentFiles\cs\netstandard2.0\ + + + + + + diff --git a/src/Testing/src/TestFileOutputContext.cs b/src/Testing/src/TestFileOutputContext.cs index 99cd30c97b9e..d8576a595ba3 100644 --- a/src/Testing/src/TestFileOutputContext.cs +++ b/src/Testing/src/TestFileOutputContext.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Reflection; using System.Text; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Testing; @@ -53,10 +54,7 @@ public TestFileOutputContext(TestContext parent) public string GetUniqueFileName(string prefix, string extension) { - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } + ArgumentNullThrowHelper.ThrowIfNull(prefix); if (extension != null && !extension.StartsWith(".", StringComparison.Ordinal)) { diff --git a/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs b/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs index 5786c5c5b713..e5555cd8495e 100644 --- a/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs +++ b/src/Testing/src/xunit/EnvironmentVariableSkipConditionAttribute.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Testing; @@ -33,18 +34,9 @@ internal EnvironmentVariableSkipConditionAttribute( string variableName, params string[] values) { - if (environmentVariable == null) - { - throw new ArgumentNullException(nameof(environmentVariable)); - } - if (variableName == null) - { - throw new ArgumentNullException(nameof(variableName)); - } - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullThrowHelper.ThrowIfNull(environmentVariable); + ArgumentNullThrowHelper.ThrowIfNull(variableName); + ArgumentNullThrowHelper.ThrowIfNull(values); _variableName = variableName; _values = values; diff --git a/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs b/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs index 3970804461a5..67a853d8b199 100644 --- a/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs +++ b/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs @@ -27,10 +27,7 @@ public void AddColumns(params string[] names) public void AddRow(params string[] values) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } + ArgumentNullException.ThrowIfNull(values); if (!_columns.Any()) { diff --git a/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs b/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs index 186a7b548e3d..ed3bef3d58eb 100644 --- a/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs +++ b/src/WebEncoders/src/EncoderServiceCollectionExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Microsoft.Extensions.WebEncoders; @@ -22,10 +23,7 @@ public static class EncoderServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddWebEncoders(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); services.AddOptions(); @@ -50,15 +48,8 @@ public static IServiceCollection AddWebEncoders(this IServiceCollection services /// The so that additional calls can be chained. public static IServiceCollection AddWebEncoders(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); services.AddWebEncoders(); services.Configure(setupAction); diff --git a/src/WebEncoders/src/Microsoft.Extensions.WebEncoders.csproj b/src/WebEncoders/src/Microsoft.Extensions.WebEncoders.csproj index 13b3a521af7f..05be3a43b326 100644 --- a/src/WebEncoders/src/Microsoft.Extensions.WebEncoders.csproj +++ b/src/WebEncoders/src/Microsoft.Extensions.WebEncoders.csproj @@ -1,4 +1,4 @@ - + Contains registration and configuration APIs to add the core framework encoders to a dependency injection container. @@ -20,4 +20,9 @@ + + + + + diff --git a/src/WebEncoders/src/Testing/HtmlTestEncoder.cs b/src/WebEncoders/src/Testing/HtmlTestEncoder.cs index 596a12c6f8d6..476bed2fd302 100644 --- a/src/WebEncoders/src/Testing/HtmlTestEncoder.cs +++ b/src/WebEncoders/src/Testing/HtmlTestEncoder.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.WebEncoders.Testing; @@ -21,10 +22,7 @@ public override int MaxOutputCharactersPerInputCharacter /// public override string Encode(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); if (value.Length == 0) { @@ -37,15 +35,8 @@ public override string Encode(string value) /// public override void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) { @@ -60,15 +51,8 @@ public override void Encode(TextWriter output, char[] value, int startIndex, int /// public override void Encode(TextWriter output, string value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) { diff --git a/src/WebEncoders/src/Testing/JavaScriptTestEncoder.cs b/src/WebEncoders/src/Testing/JavaScriptTestEncoder.cs index 92ed47faad21..805bd70e30d4 100644 --- a/src/WebEncoders/src/Testing/JavaScriptTestEncoder.cs +++ b/src/WebEncoders/src/Testing/JavaScriptTestEncoder.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.WebEncoders.Testing; @@ -21,10 +22,7 @@ public override int MaxOutputCharactersPerInputCharacter /// public override string Encode(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); if (value.Length == 0) { @@ -37,15 +35,8 @@ public override string Encode(string value) /// public override void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) { @@ -60,15 +51,8 @@ public override void Encode(TextWriter output, char[] value, int startIndex, int /// public override void Encode(TextWriter output, string value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) { diff --git a/src/WebEncoders/src/Testing/UrlTestEncoder.cs b/src/WebEncoders/src/Testing/UrlTestEncoder.cs index e5c71fa730a5..1bde585ca0a8 100644 --- a/src/WebEncoders/src/Testing/UrlTestEncoder.cs +++ b/src/WebEncoders/src/Testing/UrlTestEncoder.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.WebEncoders.Testing; @@ -21,10 +22,7 @@ public override int MaxOutputCharactersPerInputCharacter /// public override string Encode(string value) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); if (value.Length == 0) { @@ -37,15 +35,8 @@ public override string Encode(string value) /// public override void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) { @@ -60,15 +51,8 @@ public override void Encode(TextWriter output, char[] value, int startIndex, int /// public override void Encode(TextWriter output, string value, int startIndex, int characterCount) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(output); + ArgumentNullThrowHelper.ThrowIfNull(value); if (characterCount == 0) {