From 09561bb2d49bb46ca1a81c92ec57ab88d301c060 Mon Sep 17 00:00:00 2001 From: martincostello Date: Sat, 23 Nov 2024 13:37:41 +0000 Subject: [PATCH] Fix NotSupportedException in AoT project Fix `NotSupportedException` being thrown with .NET 9 when accessing `ModelMetadata.ElementType` in a native AoT application due to `Microsoft.AspNetCore.Mvc.ApiExplorer.IsEnhancedModelMetadataSupported` being disabled. --- .../ApiParameterDescriptionExtensions.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/ApiParameterDescriptionExtensions.cs b/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/ApiParameterDescriptionExtensions.cs index a36ed4c778..d2143bcf10 100644 --- a/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/ApiParameterDescriptionExtensions.cs +++ b/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/ApiParameterDescriptionExtensions.cs @@ -113,8 +113,17 @@ internal static bool IsFromBody(this ApiParameterDescription apiParameter) internal static bool IsFromForm(this ApiParameterDescription apiParameter) { + bool isEnhancedModelMetadataSupported = true; + +#if NET9_0_OR_GREATER + if (AppContext.TryGetSwitch("Microsoft.AspNetCore.Mvc.ApiExplorer.IsEnhancedModelMetadataSupported", out var isEnabled)) + { + isEnhancedModelMetadataSupported = isEnabled; + } +#endif + var source = apiParameter.Source; - var elementType = apiParameter.ModelMetadata?.ElementType; + var elementType = isEnhancedModelMetadataSupported ? apiParameter.ModelMetadata?.ElementType : null; return (source == BindingSource.Form || source == BindingSource.FormFile) || (elementType != null && typeof(IFormFile).IsAssignableFrom(elementType));