Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Allow to use swagger for frontent API / generate openapi
supportfe60c23014b1
diff --git a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs b/src/API/Grand.Api/Extensions/AddParamOperationFilter.csindex 843dd9e8d..c327b8361 100644--- a/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs+++ b/src/API/Grand.Api/Extensions/AddParamOperationFilter.cs@@ -1,4 +1,6 @@-using Microsoft.OpenApi.Models;+using MassTransit.Internals;+using Microsoft.AspNetCore.Mvc;+using Microsoft.OpenApi.Models;using Swashbuckle.AspNetCore.SwaggerGen;namespace Grand.Api.Extensions@@ -7,66 +9,90 @@ namespace Grand.Api.Extensions{public void Apply(OpenApiOperation operation, OperationFilterContext context){- if (context.ApiDescription.GroupName == "v1" && context.ApiDescription.HttpMethod == "GET" && context.ApiDescription.ParameterDescriptions.Count == 0)+ if (context.ApiDescription.GroupName == "v1" && context.ApiDescription.HttpMethod == "GET" &&+ context.ApiDescription.ParameterDescriptions.Count == 0){ApplyV1(operation, context);}++ if (context.ApiDescription.GroupName == "v2" && context.ApiDescription.HttpMethod == "POST")+ {+ ApplyV2(operation, context);+ }}private void ApplyV1(OpenApiOperation operation, OperationFilterContext context){operation.Parameters.Add(new OpenApiParameter() {- Name = "$top",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Show only the first n items.",- Required = false,- Schema = new OpenApiSchema() {- Minimum = 0,- Type = "integer"- }- });- operation.Parameters.Add(new OpenApiParameter() {- Name = "$skip",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Skip the first n items",- Required = false,- Schema = new OpenApiSchema() {- Minimum = 0,- Type = "integer"- }- });- operation.Parameters.Add(new OpenApiParameter() {- Name = "$count",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Include count of items",- Required = false,- Schema = new OpenApiSchema() {- Type = "boolean"- }- });- operation.Parameters.Add(new OpenApiParameter() {- Name = "$orderby",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Order items by property values",- Required = false,- Schema = new OpenApiSchema() {- Type = "string"- }- });- operation.Parameters.Add(new OpenApiParameter() {- Name = "$filter",- AllowReserved = true,- In = ParameterLocation.Query,- Description = "Filter items by property values",- Required = false,- Schema = new OpenApiSchema() {- Type = "string"+ Name = "$top",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Show only the first n items.",+ Required = false,+ Schema = new OpenApiSchema() {+ Minimum = 0,+ Type = "integer"+ }+ });+ operation.Parameters.Add(new OpenApiParameter() {+ Name = "$skip",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Skip the first n items",+ Required = false,+ Schema = new OpenApiSchema() {+ Minimum = 0,+ Type = "integer"+ }+ });+ operation.Parameters.Add(new OpenApiParameter() {+ Name = "$count",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Include count of items",+ Required = false,+ Schema = new OpenApiSchema() {+ Type = "boolean"+ }+ });+ operation.Parameters.Add(new OpenApiParameter() {+ Name = "$orderby",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Order items by property values",+ Required = false,+ Schema = new OpenApiSchema() {+ Type = "string"+ }+ });+ operation.Parameters.Add(new OpenApiParameter() {+ Name = "$filter",+ AllowReserved = true,+ In = ParameterLocation.Query,+ Description = "Filter items by property values",+ Required = false,+ Schema = new OpenApiSchema() {+ Type = "string"+ }+ });+ }++ private void ApplyV2(OpenApiOperation operation, OperationFilterContext context)+ {+ operation.Parameters ??= new List<OpenApiParameter>();++ if (context.MethodInfo.GetAttribute<AutoValidateAntiforgeryTokenAttribute>().Any())+ {+ operation.Parameters.Add(new OpenApiParameter {+ Name = "X-CSRF-TOKEN",+ In = ParameterLocation.Header,+ Required = true,+ Schema = new OpenApiSchema {+ Type = "string",+ Description = "Antiforgery token"}});+ }}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/ApiExplorer/ApiParameterContext.cs b/src/Web/Grand.Web.Common/ApiExplorer/ApiParameterContext.csnew file mode 100644index 000000000..5750271a4--- /dev/null+++ b/src/Web/Grand.Web.Common/ApiExplorer/ApiParameterContext.cs@@ -0,0 +1,31 @@+//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/ApiParameterContext.cs++using Microsoft.AspNetCore.Mvc.ApiExplorer;+using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.ModelBinding;+using Microsoft.AspNetCore.Routing.Template;++namespace Grand.Web.Common.ApiExplorer;++public class ApiParameterContext+{+ public ApiParameterContext(+ IModelMetadataProvider metadataProvider,+ ControllerActionDescriptor actionDescriptor,+ IReadOnlyList<TemplatePart> routeParameters)+ {+ MetadataProvider = metadataProvider;+ ActionDescriptor = actionDescriptor;+ RouteParameters = routeParameters;++ Results = new List<ApiParameterDescription>();+ }++ public ControllerActionDescriptor ActionDescriptor { get; }++ public IModelMetadataProvider MetadataProvider { get; }++ public IList<ApiParameterDescription> Results { get; }++ public IReadOnlyList<TemplatePart> RouteParameters { get; }+}diff --git a/src/Web/Grand.Web.Common/ApiExplorer/ApiResponseTypeProvider.cs b/src/Web/Grand.Web.Common/ApiExplorer/ApiResponseTypeProvider.csnew file mode 100644index 000000000..9bd822a2a--- /dev/null+++ b/src/Web/Grand.Web.Common/ApiExplorer/ApiResponseTypeProvider.cs@@ -0,0 +1,349 @@+//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/ApiResponseTypeProvider.cs++using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.ApiExplorer;+using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.Formatters;+using Microsoft.AspNetCore.Mvc.Infrastructure;+using Microsoft.AspNetCore.Mvc.ModelBinding;++namespace Grand.Web.Common.ApiExplorer;++public class ApiResponseTypeProvider+{+ private readonly IModelMetadataProvider _modelMetadataProvider;+ private readonly IActionResultTypeMapper _mapper;+ private readonly MvcOptions _mvcOptions;++ public ApiResponseTypeProvider(+ IModelMetadataProvider modelMetadataProvider,+ IActionResultTypeMapper mapper,+ MvcOptions mvcOptions)+ {+ _modelMetadataProvider = modelMetadataProvider;+ _mapper = mapper;+ _mvcOptions = mvcOptions;+ }++ public ICollection<ApiResponseType> GetApiResponseTypes(ControllerActionDescriptor action)+ {+ // We only provide response info if we can figure out a type that is a user-data type.+ // Void /Task object/IActionResult will result in no data.+ var declaredReturnType = GetDeclaredReturnType(action);++ var runtimeReturnType = GetRuntimeReturnType(declaredReturnType);++ var responseMetadataAttributes = GetResponseMetadataAttributes(action);+ if (!HasSignificantMetadataProvider(responseMetadataAttributes) &&+ action.Properties.TryGetValue(typeof(ApiConventionResult), out var result))+ {+ // Action does not have any conventions. Use conventions on it if present.+ var apiConventionResult = (ApiConventionResult)result!;+ responseMetadataAttributes.AddRange(apiConventionResult.ResponseMetadataProviders);+ }++ var defaultErrorType = typeof(void);+ if (action.Properties.TryGetValue(typeof(ProducesErrorResponseTypeAttribute), out result))+ {+ defaultErrorType = ((ProducesErrorResponseTypeAttribute)result!).Type;+ }++ var apiResponseTypes = GetApiResponseTypes(responseMetadataAttributes, runtimeReturnType, defaultErrorType);+ return apiResponseTypes;+ }++ private static List<IApiResponseMetadataProvider> GetResponseMetadataAttributes(ControllerActionDescriptor action)+ {+ if (action.FilterDescriptors == null)+ {+ return new List<IApiResponseMetadataProvider>();+ }++ // This technique for enumerating filters will intentionally ignore any filter that is an IFilterFactory+ // while searching for a filter that implements IApiResponseMetadataProvider.+ //+ // The workaround for that is to implement the metadata interface on the IFilterFactory.+ return action.FilterDescriptors+ .Select(fd => fd.Filter)+ .OfType<IApiResponseMetadataProvider>()+ .ToList();+ }++ private ICollection<ApiResponseType> GetApiResponseTypes(+ IReadOnlyList<IApiResponseMetadataProvider> responseMetadataAttributes,+ Type? type,+ Type defaultErrorType)+ {+ var contentTypes = new MediaTypeCollection();+ var responseTypeMetadataProviders = _mvcOptions.OutputFormatters.OfType<IApiResponseTypeMetadataProvider>();++ var responseTypes = ReadResponseMetadata(+ responseMetadataAttributes,+ type,+ defaultErrorType,+ contentTypes,+ responseTypeMetadataProviders);++ // Set the default status only when no status has already been set explicitly+ if (responseTypes.Count == 0 && type != null)+ {+ responseTypes.Add(new ApiResponseType {+ StatusCode = StatusCodes.Status200OK,+ Type = type,+ });+ }++ if (contentTypes.Count == 0)+ {+ // None of the IApiResponseMetadataProvider specified a content type. This is common for actions that+ // specify one or more ProducesResponseType but no ProducesAttribute. In this case, formatters will participate in conneg+ // and respond to the incoming request.+ // Querying IApiResponseTypeMetadataProvider.GetSupportedContentTypes with "null" should retrieve all supported+ // content types that each formatter may respond in.+ contentTypes.Add((string)null!);+ }++ foreach (var apiResponse in responseTypes)+ {+ CalculateResponseFormatForType(apiResponse, contentTypes, responseTypeMetadataProviders,+ _modelMetadataProvider);+ }++ return responseTypes;+ }++ private static ApiResponseFormat CreateDefaultApiResponseFormat()+ {+ return new ApiResponseFormat { MediaType = "application/json" };+ }+ // Shared with EndpointMetadataApiDescriptionProvider+ internal static List<ApiResponseType> ReadResponseMetadata(+ IReadOnlyList<IApiResponseMetadataProvider> responseMetadataAttributes,+ Type? type,+ Type defaultErrorType,+ MediaTypeCollection contentTypes,+ IEnumerable<IApiResponseTypeMetadataProvider>? responseTypeMetadataProviders = null,+ IModelMetadataProvider? modelMetadataProvider = null)+ {+ var results = new Dictionary<int, ApiResponseType>();++ // Get the content type that the action explicitly set to support.+ // Walk through all 'filter' attributes in order, and allow each one to see or override+ // the results of the previous ones. This is similar to the execution path for content-negotiation.+ if (responseMetadataAttributes != null)+ {+ foreach (var metadataAttribute in responseMetadataAttributes)+ {+ // All ProducesXAttributes, except for ProducesResponseTypeAttribute do+ // not allow multiple instances on the same method/class/etc. For those+ // scenarios, the `SetContentTypes` method on the attribute continuously+ // clears out more general content types in favor of more specific ones+ // since we iterate through the attributes in order. For example, if a+ // Produces exists on both a controller and an action within the controller,+ // we favor the definition in the action. This is a semantic that does not+ // apply to ProducesResponseType, which allows multiple instances on an target.+ if (metadataAttribute is not ProducesResponseTypeAttribute)+ {+ metadataAttribute.SetContentTypes(contentTypes);+ }++ var statusCode = metadataAttribute.StatusCode;++ var apiResponseType = new ApiResponseType {+ Type = metadataAttribute.Type,+ StatusCode = statusCode,+ IsDefaultResponse = metadataAttribute is IApiDefaultResponseMetadataProvider,+ };++ if (apiResponseType.Type == typeof(void))+ {+ if (type != null && (statusCode == StatusCodes.Status200OK ||+ statusCode == StatusCodes.Status201Created))+ {+ // ProducesResponseTypeAttribute's constructor defaults to setting "Type" to void when no value is specified.+ // In this event, use the action's return type for 200 or 201 status codes. This lets you decorate an action with a+ // [ProducesResponseType(201)] instead of [ProducesResponseType(typeof(Person), 201] when typeof(Person) can be inferred+ // from the return type.+ apiResponseType.Type = type;+ }+ /*else if (IsClientError(statusCode))+ {+ // Determine whether or not the type was provided by the user. If so, favor it over the default+ // error type for 4xx client errors if no response type is specified..+ var setByDefault = metadataAttribute is ProducesResponseTypeAttribute {+ IsResponseTypeSetByDefault: true+ };+ apiResponseType.Type = setByDefault ? defaultErrorType : apiResponseType.Type;+ }*/+ else if (apiResponseType.IsDefaultResponse)+ {+ apiResponseType.Type = defaultErrorType;+ }+ }++ // We special case the handling of ProcuesResponseTypeAttributes since+ // multiple ProducesResponseTypeAttributes are permitted on a single+ // action/controller/etc. In that scenario, instead of picking the most-specific+ // set of content types (like we do with the Produces attribute above) we process+ // the content types for each attribute independently.+ if (metadataAttribute is ProducesResponseTypeAttribute)+ {+ var attributeContentTypes = new MediaTypeCollection();+ metadataAttribute.SetContentTypes(attributeContentTypes);+ CalculateResponseFormatForType(apiResponseType, attributeContentTypes,+ responseTypeMetadataProviders, modelMetadataProvider);+ }++ if (apiResponseType.Type != null)+ {+ results[apiResponseType.StatusCode] = apiResponseType;+ }+ }+ }++ return results.Values.ToList();+ }++ // Shared with EndpointMetadataApiDescriptionProvider+ internal static void CalculateResponseFormatForType(ApiResponseType apiResponse,+ MediaTypeCollection declaredContentTypes,+ IEnumerable<IApiResponseTypeMetadataProvider>? responseTypeMetadataProviders,+ IModelMetadataProvider? modelMetadataProvider)+ {+ // If response formats have already been calculate for this type,+ // then exit early. This avoids populating the ApiResponseFormat for+ // types that have already been handled, specifically ProducesResponseTypes.+ if (apiResponse.ApiResponseFormats.Count > 0)+ {+ return;+ }++ // Given the content-types that were declared for this action, determine the formatters that support the content-type for the given+ // response type.+ // 1. Responses that do not specify an type do not have any associated content-type. This usually is meant for status-code only responses such+ // as return NotFound();+ // 2. When a type is specified, use GetSupportedContentTypes to expand wildcards and get the range of content-types formatters support.+ // 3. When no formatter supports the specified content-type, use the user specified value as is. This is useful in actions where the user+ // dictates the content-type.+ // e.g. [Produces("application/pdf")] Action() => FileStream("somefile.pdf", "application/pdf");+ var responseType = apiResponse.Type;+ if (responseType == null || responseType == typeof(void))+ {+ return;+ }++ apiResponse.ModelMetadata = modelMetadataProvider?.GetMetadataForType(responseType);++ foreach (var contentType in declaredContentTypes)+ {+ var isSupportedContentType = false;++ if (responseTypeMetadataProviders != null)+ {+ foreach (var responseTypeMetadataProvider in responseTypeMetadataProviders)+ {+ var formatterSupportedContentTypes = responseTypeMetadataProvider.GetSupportedContentTypes(+ contentType,+ responseType);++ if (formatterSupportedContentTypes == null)+ {+ continue;+ }++ isSupportedContentType = true;++ foreach (var formatterSupportedContentType in formatterSupportedContentTypes)+ {+ apiResponse.ApiResponseFormats.Add(new ApiResponseFormat {+ Formatter = (IOutputFormatter)responseTypeMetadataProvider,+ MediaType = formatterSupportedContentType,+ });+ }+ }+ }+++ if (!isSupportedContentType && contentType != null)+ {+ // No output formatter was found that supports this content type. Add the user specified content type as-is to the result.+ apiResponse.ApiResponseFormats.Add(new ApiResponseFormat {+ MediaType = contentType,+ });+ }+ }+ }++ private Type? GetDeclaredReturnType(ControllerActionDescriptor action)+ {+ var declaredReturnType = action.MethodInfo.ReturnType;+ if (declaredReturnType == typeof(void) ||+ declaredReturnType == typeof(Task) ||+ declaredReturnType == typeof(ValueTask))+ {+ return typeof(void);+ }++ // Unwrap the type if it's a Task<T>. The Task (non-generic) case was already handled.+ var unwrappedType = declaredReturnType;+ if (declaredReturnType.IsGenericType &&+ (declaredReturnType.GetGenericTypeDefinition() == typeof(Task<>) ||+ declaredReturnType.GetGenericTypeDefinition() == typeof(ValueTask<>)))+ {+ unwrappedType = declaredReturnType.GetGenericArguments()[0];+ }++ // If the method is declared to return IActionResult or a derived class, that information+ // isn't valuable to the formatter.+ if (typeof(IActionResult).IsAssignableFrom(unwrappedType))+ {+ return null;+ }++ // If we get here, the type should be a user-defined data type or an envelope type+ // like ActionResult<T>. The mapper service will unwrap envelopes.+ unwrappedType = _mapper.GetResultDataType(unwrappedType);+ return unwrappedType;+ }++ private Type? GetRuntimeReturnType(Type? declaredReturnType)+ {+ // If we get here, then a filter didn't give us an answer, so we need to figure out if we+ // want to use the declared return type.+ //+ // We've already excluded Task, void, and IActionResult at this point.+ //+ // If the action might return any object, then assume we don't know anything about it.+ if (declaredReturnType == typeof(object))+ {+ return null;+ }++ return declaredReturnType;+ }++ private static bool IsClientError(int statusCode)+ {+ return statusCode >= 400 && statusCode < 500;+ }++ private static bool HasSignificantMetadataProvider(IReadOnlyList<IApiResponseMetadataProvider> providers)+ {+ for (var i = 0; i < providers.Count; i++)+ {+ var provider = providers[i];++ if (provider is ProducesAttribute producesAttribute && producesAttribute.Type is null)+ {+ // ProducesAttribute that does not specify type is considered not significant.+ continue;+ }++ // Any other IApiResponseMetadataProvider is considered significant+ return true;+ }++ return false;+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/ApiExplorer/MetadataApiDescriptionProvider.cs b/src/Web/Grand.Web.Common/ApiExplorer/MetadataApiDescriptionProvider.csnew file mode 100644index 000000000..281ebdeff--- /dev/null+++ b/src/Web/Grand.Web.Common/ApiExplorer/MetadataApiDescriptionProvider.cs@@ -0,0 +1,672 @@+//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs++using Grand.SharedKernel.Extensions;+using Grand.Web.Common.Attributes;+using Grand.Web.Common.Controllers;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Abstractions;+using Microsoft.AspNetCore.Mvc.ActionConstraints;+using Microsoft.AspNetCore.Mvc.ApiExplorer;+using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.Formatters;+using Microsoft.AspNetCore.Mvc.Infrastructure;+using Microsoft.AspNetCore.Mvc.ModelBinding;+using Microsoft.AspNetCore.Routing;+using Microsoft.AspNetCore.Routing.Template;+using Microsoft.Extensions.Options;+using System.Reflection;++namespace Grand.Web.Common.ApiExplorer;++public class MetadataApiDescriptionProvider : IApiDescriptionProvider+{+ private readonly MvcOptions _mvcOptions;+ private readonly RouteOptions _routeOptions;+ private readonly IInlineConstraintResolver _constraintResolver;+ private readonly IModelMetadataProvider _modelMetadataProvider;+ private readonly ApiResponseTypeProvider _responseTypeProvider;++ /// <summary>+ /// Creates a new instance of <see cref="DefaultApiDescriptionProvider"/>.+ /// </summary>+ /// <param name="optionsAccessor">The accessor for <see cref="MvcOptions"/>.</param>+ /// <param name="constraintResolver">The <see cref="IInlineConstraintResolver"/> used for resolving inline+ /// constraints.</param>+ /// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param>+ /// <param name="mapper">The <see cref="IActionResultTypeMapper"/>.</param>+ /// <param name="routeOptions">The accessor for <see cref="RouteOptions"/>.</param>+ /// <remarks>The <paramref name="mapper"/> parameter is currently ignored.</remarks>+ public MetadataApiDescriptionProvider(+ IOptions<MvcOptions> optionsAccessor,+ IInlineConstraintResolver constraintResolver,+ IModelMetadataProvider modelMetadataProvider,+ IActionResultTypeMapper mapper,+ IOptions<RouteOptions> routeOptions)+ {+ _mvcOptions = optionsAccessor.Value;+ _constraintResolver = constraintResolver;+ _modelMetadataProvider = modelMetadataProvider;+ _responseTypeProvider = new ApiResponseTypeProvider(modelMetadataProvider, mapper, _mvcOptions);+ _routeOptions = routeOptions.Value;+ }++ /// <inheritdoc />+ public int Order => -1000;++ /// <inheritdoc />+ public void OnProvidersExecuting(ApiDescriptionProviderContext context)+ {+ if (context == null)+ {+ throw new ArgumentNullException(nameof(context));+ }++ foreach (var action in context.Actions.OfType<ControllerActionDescriptor>())+ {+ if (action.ControllerTypeInfo.BaseType != typeof(BasePublicController))+ continue;++ if (action.MethodInfo.GetCustomAttributes<IgnoreApiAttribute>(true).Any())+ continue;++ if (action.AttributeRouteInfo is { SuppressPathMatching: true })+ {+ continue;+ }++ var httpMethods = GetHttpMethods(action);+ foreach (var httpMethod in httpMethods)+ {+ context.Results.Add(CreateApiDescription(action, httpMethod, "v2"));+ }+ }+ }++ /// <inheritdoc />+ public void OnProvidersExecuted(ApiDescriptionProviderContext context)+ {+ }++ private ApiDescription CreateApiDescription(+ ControllerActionDescriptor action,+ string? httpMethod,+ string? groupName)+ {+ var parsedTemplate = ParseTemplate(action);+ var path = GetRelativePath(action, parsedTemplate);++ var apiDescription = new ApiDescription() {+ ActionDescriptor = action,+ GroupName = groupName,+ HttpMethod = httpMethod,+ RelativePath = path,+ };++ var templateParameters = parsedTemplate?.Parameters?.ToList() ?? new List<TemplatePart>();++ var parameterContext = new ApiParameterContext(_modelMetadataProvider, action, templateParameters);++ foreach (var parameter in GetParameters(parameterContext))+ {+ apiDescription.ParameterDescriptions.Add(parameter);+ }++ var requestMetadataAttributes = GetRequestMetadataAttributes(action);++ var apiResponseTypes = _responseTypeProvider.GetApiResponseTypes(action);+ foreach (var apiResponseType in apiResponseTypes)+ {+ apiDescription.SupportedResponseTypes.Add(apiResponseType);+ }++ // It would be possible here to configure an action with multiple body parameters, in which case you+ // could end up with duplicate data.+ if (apiDescription.ParameterDescriptions.Count > 0)+ {+ var contentTypes = GetDeclaredContentTypes(requestMetadataAttributes);+ foreach (var parameter in apiDescription.ParameterDescriptions)+ {+ if (parameter.Source == BindingSource.Body ||+ parameter.Source == BindingSource.Form )+ {+ // For request body bound parameters, determine the content types supported+ // by input formatters.+ var requestFormats = GetSupportedFormats(contentTypes, parameter.Type);+ foreach (var format in requestFormats)+ {+ apiDescription.SupportedRequestFormats.Add(format);+ }+ }+ else if (parameter.Source == BindingSource.FormFile)+ {+ // Add all declared media types since FormFiles do not get processed by formatters.+ foreach (var contentType in contentTypes)+ {+ apiDescription.SupportedRequestFormats.Add(new ApiRequestFormat {+ MediaType = contentType,+ });+ }+ }+ }+ }++ return apiDescription;+ }++ private IList<ApiParameterDescription> GetParameters(ApiParameterContext context)+ {+ // First, get parameters from the model-binding/parameter-binding side of the world.+ if (context.ActionDescriptor.Parameters != null)+ {+ foreach (var actionParameter in context.ActionDescriptor.Parameters)+ {+ var visitor = new PseudoModelBindingVisitor(context, actionParameter);++ ModelMetadata metadata;+ if (actionParameter is ControllerParameterDescriptor controllerParameterDescriptor &&+ _modelMetadataProvider is ModelMetadataProvider provider)+ {+ // The default model metadata provider derives from ModelMetadataProvider+ // and can therefore supply information about attributes applied to parameters.+ metadata = provider.GetMetadataForParameter(controllerParameterDescriptor.ParameterInfo);+ }+ else+ {+ // For backward compatibility, if there's a custom model metadata provider that+ // only implements the older IModelMetadataProvider interface, access the more+ // limited metadata information it supplies. In this scenario, validation attributes+ // are not supported on parameters.+ metadata = _modelMetadataProvider.GetMetadataForType(actionParameter.ParameterType);+ }++ if (actionParameter.BindingInfo == null &&+ !CommonHelper.IsSimpleType(actionParameter.ParameterType))+ {+ actionParameter.BindingInfo = new BindingInfo+ {+ BindingSource = new BindingSource("Body", "Body", true, true)+ };+ }++ var bindingContext = new ApiParameterDescriptionContext(+ metadata,+ actionParameter.BindingInfo,+ propertyName: actionParameter.Name);+ visitor.WalkParameter(bindingContext);+ }+ }++ if (context.ActionDescriptor.BoundProperties != null)+ {+ foreach (var actionParameter in context.ActionDescriptor.BoundProperties)+ {+ var visitor = new PseudoModelBindingVisitor(context, actionParameter);+ var modelMetadata = context.MetadataProvider.GetMetadataForProperty(+ containerType: context.ActionDescriptor.ControllerTypeInfo.AsType(),+ propertyName: actionParameter.Name);++ var bindingContext = new ApiParameterDescriptionContext(+ modelMetadata,+ actionParameter.BindingInfo,+ propertyName: actionParameter.Name);++ visitor.WalkParameter(bindingContext);+ }+ }++ for (var i = context.Results.Count - 1; i >= 0; i--)+ {+ // Remove any 'hidden' parameters. These are things that can't come from user input,+ // so they aren't worth showing.+ if (!context.Results[i].Source.IsFromRequest)+ {+ context.Results.RemoveAt(i);+ }+ }++ // Next, we want to join up any route parameters with those discovered from the action's parameters.+ // This will result us in creating a parameter representation for each route parameter that does not+ // have a mapping parameter or bound property.+ ProcessRouteParameters(context);++ // Set IsRequired=true+ ProcessIsRequired(context, _mvcOptions);++ // Set DefaultValue+ ProcessParameterDefaultValue(context);++ return context.Results;+ }++ private void ProcessRouteParameters(ApiParameterContext context)+ {+ var routeParameters = new Dictionary<string, ApiParameterRouteInfo>(StringComparer.OrdinalIgnoreCase);+ foreach (var routeParameter in context.RouteParameters)+ {+ routeParameters.Add(routeParameter.Name!, CreateRouteInfo(routeParameter));+ }++ foreach (var parameter in context.Results)+ {+ if (parameter.Source == BindingSource.Path ||+ parameter.Source == BindingSource.ModelBinding ||+ parameter.Source == BindingSource.Custom)+ {+ if (routeParameters.TryGetValue(parameter.Name, out var routeInfo))+ {+ parameter.RouteInfo = routeInfo;+ routeParameters.Remove(parameter.Name);++ if (parameter.Source == BindingSource.ModelBinding &&+ !parameter.RouteInfo.IsOptional)+ {+ // If we didn't see any information about the parameter, but we have+ // a route parameter that matches, let's switch it to path.+ parameter.Source = BindingSource.Path;+ }+ }+ }+ }++ // Lastly, create a parameter representation for each route parameter that did not find+ // a partner.+ foreach (var routeParameter in routeParameters)+ {+ context.Results.Add(new ApiParameterDescription() {+ Name = routeParameter.Key,+ RouteInfo = routeParameter.Value,+ Source = BindingSource.Path,+ });+ }+ }++ internal static void ProcessIsRequired(ApiParameterContext context, MvcOptions mvcOptions)+ {+ foreach (var parameter in context.Results)+ {+ if (parameter.Source == BindingSource.Body)+ {+ if (parameter.BindingInfo == null ||+ parameter.BindingInfo.EmptyBodyBehavior == EmptyBodyBehavior.Default)+ {+ parameter.IsRequired = !mvcOptions.AllowEmptyInputInBodyModelBinding;+ }+ else+ {+ parameter.IsRequired = parameter.BindingInfo.EmptyBodyBehavior != EmptyBodyBehavior.Allow;+ }+ }++ if (parameter.ModelMetadata != null && parameter.ModelMetadata.IsBindingRequired)+ {+ parameter.IsRequired = true;+ }++ if (parameter.Source == BindingSource.Path && parameter.RouteInfo != null &&+ !parameter.RouteInfo.IsOptional)+ {+ parameter.IsRequired = true;+ }+ }+ }++ internal static void ProcessParameterDefaultValue(ApiParameterContext context)+ {+ foreach (var parameter in context.Results)+ {+ if (parameter.Source == BindingSource.Path)+ {+ parameter.DefaultValue = parameter.RouteInfo?.DefaultValue;+ }+ /*else+ {+ if (parameter.ParameterDescriptor is ControllerParameterDescriptor controllerParameter &&+ ParameterDefaultValues.TryGetDeclaredParameterDefaultValue(controllerParameter.ParameterInfo,+ out var defaultValue))+ {+ parameter.DefaultValue = defaultValue;+ }+ }*/+ }+ }++ private ApiParameterRouteInfo CreateRouteInfo(TemplatePart routeParameter)+ {+ var constraints = new List<IRouteConstraint>();+ if (routeParameter.InlineConstraints != null)+ {+ foreach (var constraint in routeParameter.InlineConstraints)+ {+ constraints.Add(_constraintResolver.ResolveConstraint(constraint.Constraint)!);+ }+ }++ return new ApiParameterRouteInfo() {+ Constraints = constraints,+ DefaultValue = routeParameter.DefaultValue,+ IsOptional = routeParameter.IsOptional || routeParameter.DefaultValue != null,+ };+ }++ private static IEnumerable<string?> GetHttpMethods(ControllerActionDescriptor action)+ {+ if (action.ActionConstraints != null && action.ActionConstraints.Count > 0)+ {+ return action.ActionConstraints.OfType<HttpMethodActionConstraint>().SelectMany(c => c.HttpMethods);+ }+ else+ {+ return new string?[] { null };+ }+ }++ private static RouteTemplate? ParseTemplate(ControllerActionDescriptor action)+ {+ if (action.AttributeRouteInfo?.Template != null)+ {+ return TemplateParser.Parse(action.AttributeRouteInfo.Template);+ }++ var x = action.EndpointMetadata.FirstOrDefault();++ return null;+ }++ private string? GetRelativePath(ControllerActionDescriptor action, RouteTemplate? parsedTemplate)+ {+ if (parsedTemplate == null)+ {+ return $"/{action.ControllerName}/{action.ActionName}";+ }++ var segments = new List<string>();++ foreach (var segment in parsedTemplate.Segments)+ {+ var currentSegment = string.Empty;+ foreach (var part in segment.Parts)+ {+ if (part.IsLiteral)+ {+ currentSegment += _routeOptions.LowercaseUrls ? part.Text!.ToLowerInvariant() : part.Text;+ }+ else if (part.IsParameter)+ {+ currentSegment += "{" + part.Name + "}";+ }+ }++ segments.Add(currentSegment);+ }++ return string.Join("/", segments);+ }++ private IReadOnlyList<ApiRequestFormat> GetSupportedFormats(MediaTypeCollection contentTypes, Type type)+ {+ if (contentTypes.Count == 0)+ {+ contentTypes = new MediaTypeCollection {+ "application/json",+ };+ }++ var results = new List<ApiRequestFormat>();+ foreach (var contentType in contentTypes)+ {+ foreach (var formatter in _mvcOptions.InputFormatters)+ {+ if (formatter is IApiRequestFormatMetadataProvider requestFormatMetadataProvider)+ {+ var supportedTypes = requestFormatMetadataProvider.GetSupportedContentTypes(contentType, type);++ if (supportedTypes != null)+ {+ foreach (var supportedType in supportedTypes.Where(x=>x == "application/json"))+ {+ results.Add(new ApiRequestFormat() {+ Formatter = formatter,+ MediaType = supportedType,+ });+ }+ }+ }+ }+ }++ return results;+ }++ internal static MediaTypeCollection GetDeclaredContentTypes(+ IReadOnlyList<IApiRequestMetadataProvider>? requestMetadataAttributes)+ {+ // Walk through all 'filter' attributes in order, and allow each one to see or override+ // the results of the previous ones. This is similar to the execution path for content-negotiation.+ var contentTypes = new MediaTypeCollection();+ if (requestMetadataAttributes != null)+ {+ foreach (var metadataAttribute in requestMetadataAttributes)+ {+ metadataAttribute.SetContentTypes(contentTypes);+ }+ }++ return contentTypes;+ }++ private static IApiRequestMetadataProvider[]? GetRequestMetadataAttributes(ControllerActionDescriptor action)+ {+ if (action.FilterDescriptors == null)+ {+ return null;+ }++ // This technique for enumerating filters will intentionally ignore any filter that is an IFilterFactory+ // while searching for a filter that implements IApiRequestMetadataProvider.+ //+ // The workaround for that is to implement the metadata interface on the IFilterFactory.+ return action.FilterDescriptors+ .Select(fd => fd.Filter)+ .OfType<IApiRequestMetadataProvider>()+ .ToArray();+ }++ private class ApiParameterDescriptionContext+ {+ public ModelMetadata ModelMetadata { get; }++ public string? BinderModelName { get; }++ public BindingSource? BindingSource { get; }++ public string? PropertyName { get; }++ public BindingInfo? BindingInfo { get; }++ public ApiParameterDescriptionContext(+ ModelMetadata metadata,+ BindingInfo? bindingInfo,+ string? propertyName)+ {+ // BindingMetadata can be null if the metadata represents properties.+ ModelMetadata = metadata;+ BinderModelName = bindingInfo?.BinderModelName;+ BindingSource = bindingInfo?.BindingSource;+ PropertyName = propertyName ?? metadata.Name;+ BindingInfo = bindingInfo;+ }+ }++ private class PseudoModelBindingVisitor+ {+ public PseudoModelBindingVisitor(ApiParameterContext context, ParameterDescriptor parameter)+ {+ Context = context;+ Parameter = parameter;++ Visited = new HashSet<PropertyKey>(new PropertyKeyEqualityComparer());+ }++ public ApiParameterContext Context { get; }++ public ParameterDescriptor Parameter { get; }++ // Avoid infinite recursion by tracking properties.+ private HashSet<PropertyKey> Visited { get; }++ public void WalkParameter(ApiParameterDescriptionContext context)+ {+ // Attempt to find a binding source for the parameter+ //+ // The default is ModelBinding (aka all default value providers)+ var source = BindingSource.ModelBinding;+ Visit(context, source, containerName: string.Empty);+ }++ private void Visit(+ ApiParameterDescriptionContext bindingContext,+ BindingSource ambientSource,+ string containerName)+ {+ var source = bindingContext.BindingSource;+ if (source != null && source.IsGreedy)+ {+ // We have a definite answer for this model. This is a greedy source like+ // [FromBody] so there's no need to consider properties.+ Context.Results.Add(CreateResult(bindingContext, source, containerName));+ return;+ }++ var modelMetadata = bindingContext.ModelMetadata;++ // For any property which is a leaf node, we don't want to keep traversing:+ //+ // 1) Collections - while it's possible to have binder attributes on the inside of a collection,+ // it hardly seems useful, and would result in some very weird binding.+ //+ // 2) Simple Types - These are generally part of the .net framework - primitives, or types which have a+ // type converter from string.+ //+ // 3) Types with no properties. Obviously nothing to explore there.+ //+ if (modelMetadata.IsEnumerableType ||+ !modelMetadata.IsComplexType ||+ modelMetadata.Properties.Count == 0)+ {+ Context.Results.Add(CreateResult(bindingContext, source ?? ambientSource, containerName));+ return;+ }++ // This will come from composite model binding - so investigate what's going on with each property.+ //+ // Ex:+ //+ // public IActionResult PlaceOrder(OrderDTO order) {...}+ //+ // public class OrderDTO+ // {+ // public int AccountId { get; set; }+ //+ // [FromBody]+ // public Order { get; set; }+ // }+ //+ // This should result in two parameters:+ //+ // AccountId - source: Any+ // Order - source: Body+ //++ // We don't want to append the **parameter** name when building a model name.+ var newContainerName = containerName;+ if (modelMetadata.ContainerType != null)+ {+ newContainerName = GetName(containerName, bindingContext);+ }++ var metadataProperties = modelMetadata.Properties;+ var metadataPropertiesCount = metadataProperties.Count;+ for (var i = 0; i < metadataPropertiesCount; i++)+ {+ var propertyMetadata = metadataProperties[i];+ var key = new PropertyKey(propertyMetadata, source);+ var bindingInfo = BindingInfo.GetBindingInfo(Enumerable.Empty<object>(), propertyMetadata);++ var propertyContext = new ApiParameterDescriptionContext(+ propertyMetadata,+ bindingInfo: bindingInfo,+ propertyName: null);++ if (Visited.Add(key))+ {+ Visit(propertyContext, source ?? ambientSource, newContainerName);+ Visited.Remove(key);+ }+ else+ {+ // This is cycle, so just add a result rather than traversing.+ Context.Results.Add(CreateResult(propertyContext, source ?? ambientSource, newContainerName));+ }+ }+ }++ private ApiParameterDescription CreateResult(+ ApiParameterDescriptionContext bindingContext,+ BindingSource source,+ string containerName)+ {+ return new ApiParameterDescription() {+ ModelMetadata = bindingContext.ModelMetadata,+ Name = GetName(containerName, bindingContext),+ Source = source,+ Type = bindingContext.ModelMetadata.ModelType,+ ParameterDescriptor = Parameter,+ BindingInfo = bindingContext.BindingInfo+ };+ }++ private static string GetName(string containerName, ApiParameterDescriptionContext metadata)+ {+ var propertyName = !string.IsNullOrEmpty(metadata.BinderModelName)+ ? metadata.BinderModelName+ : metadata.PropertyName;+ return ModelNames.CreatePropertyModelName(containerName, propertyName);+ }++ private readonly struct PropertyKey+ {+ public readonly Type ContainerType;++ public readonly string PropertyName;++ public readonly BindingSource? Source;++ public PropertyKey(ModelMetadata metadata, BindingSource? source)+ {+ ContainerType = metadata.ContainerType!;+ PropertyName = metadata.PropertyName!;+ Source = source;+ }+ }++ private class PropertyKeyEqualityComparer : IEqualityComparer<PropertyKey>+ {+ public bool Equals(PropertyKey x, PropertyKey y)+ {+ return+ x.ContainerType == y.ContainerType &&+ x.PropertyName == y.PropertyName &&+ x.Source == y.Source;+ }++ public int GetHashCode(PropertyKey obj)+ {+ var hashCodeCombiner = new HashCode();+ hashCodeCombiner.Add(obj.ContainerType);+ hashCodeCombiner.Add(obj.PropertyName);+ hashCodeCombiner.Add(obj.Source);+ return hashCodeCombiner.ToHashCode();+ }+ }+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/ApiProviderStartup.cs b/src/Web/Grand.Web.Common/Startup/ApiProviderStartup.csnew file mode 100644index 000000000..1f46f0bdd--- /dev/null+++ b/src/Web/Grand.Web.Common/Startup/ApiProviderStartup.cs@@ -0,0 +1,45 @@+using Grand.Infrastructure;+using Grand.Web.Common.ApiExplorer;+using Microsoft.AspNetCore.Builder;+using Microsoft.AspNetCore.Hosting;+using Microsoft.AspNetCore.Mvc.ApiExplorer;+using Microsoft.Extensions.Configuration;+using Microsoft.Extensions.DependencyInjection;+using Microsoft.Extensions.DependencyInjection.Extensions;++namespace Grand.Web.Common.Startup+{+ /// <summary>+ /// Represents object for the configuring api description provider on application+ /// </summary>+ public class ApiProviderStartup : IStartupApplication+ {+ /// <summary>+ /// Add and configure any of the middleware+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ //Swagger - api description provider+ services.TryAddEnumerable(ServiceDescriptor.Transient<IApiDescriptionProvider, MetadataApiDescriptionProvider>());+ }++ /// <summary>+ /// Configure the using of added middleware+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {++ }++ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 89;+ public bool BeforeConfigure => true;++ }+}