Skip to content

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.

Refactor API (#554)

Krzysztof Pajak7ec3e5f7c57d
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 4d3e994ac..ff913ef39 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -5,8 +5,10 @@
<ItemGroup>
<PackageVersion Include="MaxMind.GeoIP2" Version="5.2.0" />
<PackageVersion Include="ExcelMapper" Version="5.2.593" />
+ <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageVersion Include="Microsoft.FeatureManagement.AspNetCore" Version="4.0.0" />
<PackageVersion Include="NPOI" Version="2.7.2" />
+ <PackageVersion Include="Scalar.AspNetCore" Version="1.2.72" />
<PackageVersion Include="Scryber.Core" Version="6.0.4-beta" />
<PackageVersion Include="Scryber.Core.OpenType" Version="6.1.0-beta" />
<PackageVersion Include="MailKit" Version="4.9.0" />
@@ -38,13 +40,10 @@
<PackageVersion Include="FluentValidation" Version="11.11.0" />
<PackageVersion Include="Microsoft.AspNetCore.JsonPatch" Version="9.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.0" />
- <PackageVersion Include="Microsoft.AspNetCore.OData" Version="9.1.1" />
- <PackageVersion Include="MongoDB.AspNetCore.OData" Version="1.1.0" />
- <PackageVersion Include="Swashbuckle.AspNetCore" Version="7.2.0" />
- <PackageVersion Include="Swashbuckle.AspNetCore.Annotations" Version="7.2.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Facebook" Version="9.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="9.0.0" />
<PackageVersion Include="Braintree" Version="5.28.0" />
+ <PackageVersion Include="System.Linq.Dynamic.Core" Version="1.5.1" />
<PackageVersion Include="System.Xml.XPath.XmlDocument" Version="4.7.0" />
<PackageVersion Include="Stripe.net" Version="47.1.0" />
<PackageVersion Include="elFinder.Net.AspNetCore" Version="1.5.0" />
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
index c84bf95e6..b40e73808 100644
--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
@@ -5,6 +5,7 @@ using Grand.Domain.Customers;
using Grand.Infrastructure.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
@@ -34,12 +35,12 @@ public class ApiAuthenticationService : IApiAuthenticationService
if (string.IsNullOrEmpty(authHeader))
return null;
- if (_httpContextAccessor.HttpContext.Request.Path.Value != null
- && !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata"))
+ if (IsApiFrontAuthenticated())
{
customer = await ApiCustomer();
return customer;
}
+
var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return null;
@@ -55,6 +56,15 @@ public class ApiAuthenticationService : IApiAuthenticationService
return customer;
}
+ private bool IsApiFrontAuthenticated()
+ {
+ var endpoint = _httpContextAccessor.HttpContext.GetEndpoint();
+ if (endpoint == null) return false;
+
+ var authorizeAttributes = endpoint.Metadata.GetOrderedMetadata<AuthorizeAttribute>();
+ return authorizeAttributes.Any(attr => attr.AuthenticationSchemes?.Contains(FrontendAPIConfig.AuthenticationScheme) == true);
+ }
+
private async Task<Customer> ApiCustomer()
{
diff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
index 94bfde893..5b64908e2 100644
--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs
@@ -55,7 +55,6 @@ public class CookieAuthenticationService : IGrandAuthenticationService
private readonly IGroupService _groupService;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly SecurityConfig _securityConfig;
- private Customer _cachedCustomer;
#endregion
@@ -112,12 +111,8 @@ public class CookieAuthenticationService : IGrandAuthenticationService
{
_httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
- await _httpContextAccessor.HttpContext.SignInAsync(
- GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
+ await _httpContextAccessor.HttpContext.SignInAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
}
-
- //cache authenticated customer
- _cachedCustomer = customer;
}
/// <summary>
@@ -125,9 +120,6 @@ public class CookieAuthenticationService : IGrandAuthenticationService
/// </summary>
public virtual async Task SignOut()
{
- //Firstly reset cached customer
- _cachedCustomer = null;
-
//and then sign out customer from the present scheme of authentication
if (_httpContextAccessor.HttpContext != null)
{
@@ -145,15 +137,7 @@ public class CookieAuthenticationService : IGrandAuthenticationService
/// <returns>Customer</returns>
public virtual async Task<Customer> GetAuthenticatedCustomer()
{
- //check if there is a cached customer
- if (_cachedCustomer != null)
- return _cachedCustomer;
-
- //get the authenticated user identity
- if (_httpContextAccessor.HttpContext == null) return _cachedCustomer;
- var authenticateResult =
- await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults
- .AuthenticationScheme);
+ var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return null;
@@ -195,10 +179,7 @@ public class CookieAuthenticationService : IGrandAuthenticationService
if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
return null;
- //Cache the authenticated customer
- _cachedCustomer = customer;
-
- return _cachedCustomer;
+ return customer;
}
/// <summary>
diff --git a/src/Core/Grand.SharedKernel/Attributes/ApiGroupAttribute.cs b/src/Core/Grand.SharedKernel/Attributes/ApiGroupAttribute.cs
new file mode 100644
index 000000000..73967b5c2
--- /dev/null
+++ b/src/Core/Grand.SharedKernel/Attributes/ApiGroupAttribute.cs
@@ -0,0 +1,12 @@
+namespace Grand.SharedKernel.Attributes;
+
+[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
+public sealed class ApiGroupAttribute : Attribute
+{
+ public string GroupName { get; }
+
+ public ApiGroupAttribute(string groupName)
+ {
+ GroupName = groupName;
+ }
+}
\ No newline at end of file
diff --git a/src/Core/Grand.SharedKernel/Extensions/ApiConstants.cs b/src/Core/Grand.SharedKernel/Extensions/ApiConstants.cs
new file mode 100644
index 000000000..7e1d3c678
--- /dev/null
+++ b/src/Core/Grand.SharedKernel/Extensions/ApiConstants.cs
@@ -0,0 +1,7 @@
+namespace Grand.SharedKernel.Extensions;
+
+public static class ApiConstants
+{
+ public const string ApiGroupNameV1 = "v1";
+ public const string ApiGroupNameV2 = "v2";
+}
diff --git a/src/Modules/Grand.Module.Api/ApiExplorer/ApiParameterContext.cs b/src/Modules/Grand.Module.Api/ApiExplorer/ApiParameterContext.cs
deleted file mode 100644
index 1f04a920d..000000000
--- a/src/Modules/Grand.Module.Api/ApiExplorer/ApiParameterContext.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-//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.Module.Api.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; }
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/ApiExplorer/ApiResponseTypeProvider.cs b/src/Modules/Grand.Module.Api/ApiExplorer/ApiResponseTypeProvider.cs
index 07b44d8d3..caf1b36e2 100644
--- a/src/Modules/Grand.Module.Api/ApiExplorer/ApiResponseTypeProvider.cs
+++ b/src/Modules/Grand.Module.Api/ApiExplorer/ApiResponseTypeProvider.cs
@@ -1,8 +1,11 @@
-//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/ApiResponseTypeProvider.cs
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/ApiResponseTypeProvider.cs
#nullable enable
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
@@ -12,10 +15,10 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Grand.Module.Api.ApiExplorer;
-public class ApiResponseTypeProvider
+internal sealed class ApiResponseTypeProvider
{
- private readonly IActionResultTypeMapper _mapper;
private readonly IModelMetadataProvider _modelMetadataProvider;
+ private readonly IActionResultTypeMapper _mapper;
private readonly MvcOptions _mvcOptions;
public ApiResponseTypeProvider(
@@ -47,14 +50,22 @@ public class ApiResponseTypeProvider
var defaultErrorType = typeof(void);
if (action.Properties.TryGetValue(typeof(ProducesErrorResponseTypeAttribute), out result))
+ {
defaultErrorType = ((ProducesErrorResponseTypeAttribute)result!).Type;
+ }
- var apiResponseTypes = GetApiResponseTypes(responseMetadataAttributes, runtimeReturnType, defaultErrorType);
+ var producesResponseMetadata = action.EndpointMetadata.OfType<IProducesResponseTypeMetadata>().ToList();
+ var apiResponseTypes = GetApiResponseTypes(responseMetadataAttributes, producesResponseMetadata, 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.
//
@@ -66,126 +77,216 @@ public class ApiResponseTypeProvider
}
private ICollection<ApiResponseType> GetApiResponseTypes(
- IReadOnlyList<IApiResponseMetadataProvider> responseMetadataAttributes,
- Type? type,
- Type defaultErrorType)
+ IReadOnlyList<IApiResponseMetadataProvider> responseMetadataAttributes,
+ IReadOnlyList<IProducesResponseTypeMetadata> producesResponseMetadata,
+ Type? type,
+ Type defaultErrorType)
{
var contentTypes = new MediaTypeCollection();
- var responseTypeMetadataProviders = _mvcOptions.OutputFormatters
- .OfType<SystemTextJsonOutputFormatter>();
+ var responseTypeMetadataProviders = _mvcOptions.OutputFormatters.OfType<IApiResponseTypeMetadataProvider>();
var responseTypes = ReadResponseMetadata(
+ producesResponseMetadata,
+ type,
+ responseTypeMetadataProviders,
+ _modelMetadataProvider);
+
+ // Read response metadata from providers and
+ // overwrite responseTypes from the metadata based
+ // on the status code
+ var responseTypesFromProvider = ReadResponseMetadata(
responseMetadataAttributes,
type,
defaultErrorType,
contentTypes,
+ out var _,
responseTypeMetadataProviders);
+ foreach (var responseType in responseTypesFromProvider)
+ {
+ responseTypes[responseType.Key] = responseType.Value;
+ }
+
// Set the default status only when no status has already been set explicitly
if (responseTypes.Count == 0 && type != null)
- responseTypes.Add(new ApiResponseType {
+ {
+ responseTypes.Add(StatusCodes.Status200OK, new ApiResponseType {
StatusCode = StatusCodes.Status200OK,
- Type = type
+ 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);
+ foreach (var apiResponse in responseTypes.Values)
+ {
+ CalculateResponseFormatForType(apiResponse, contentTypes, responseTypeMetadataProviders, _modelMetadataProvider);
+ }
- return responseTypes;
+ return responseTypes.Values;
}
// Shared with EndpointMetadataApiDescriptionProvider
- internal static List<ApiResponseType> ReadResponseMetadata(
+ internal static Dictionary<int, ApiResponseType> ReadResponseMetadata(
IReadOnlyList<IApiResponseMetadataProvider> responseMetadataAttributes,
Type? type,
- Type defaultErrorType,
+ Type? defaultErrorType,
MediaTypeCollection contentTypes,
+ out bool errorSetByDefault,
IEnumerable<IApiResponseTypeMetadataProvider>? responseTypeMetadataProviders = null,
IModelMetadataProvider? modelMetadataProvider = null)
{
+ errorSetByDefault = false;
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.
- foreach (var metadataAttribute in responseMetadataAttributes)
+ 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 description = metadataAttribute.Description;
+
+ var apiResponseType = new ApiResponseType {
+ Type = metadataAttribute.Type,
+ StatusCode = statusCode,
+ IsDefaultResponse = metadataAttribute is IApiDefaultResponseMetadataProvider,
+ //Description = description
+ };
+
+ 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..
+ errorSetByDefault = metadataAttribute is ProducesResponseTypeAttribute { /*IsResponseTypeSetByDefault: true*/ };
+ apiResponseType.Type = errorSetByDefault ? 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;
+ }
+
+ internal static Dictionary<int, ApiResponseType> ReadResponseMetadata(
+ IReadOnlyList<IProducesResponseTypeMetadata> responseMetadata,
+ Type? type,
+ IEnumerable<IApiResponseTypeMetadataProvider>? responseTypeMetadataProviders = null,
+ IModelMetadataProvider? modelMetadataProvider = null)
+ {
+ var results = new Dictionary<int, ApiResponseType>();
+
+ foreach (var metadata in responseMetadata)
{
- // 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;
+ // `IResult` metadata inserted for awaitable types should
+ // not be considered for response metadata.
+ if (typeof(IResult).IsAssignableFrom(metadata.Type))
+ {
+ continue;
+ }
+
+ var statusCode = metadata.StatusCode;
var apiResponseType = new ApiResponseType {
- Type = metadataAttribute.Type,
+ Type = metadata.Type,
StatusCode = statusCode,
- IsDefaultResponse = metadataAttribute is IApiDefaultResponseMetadataProvider
};
- if (apiResponseType.Type == typeof(void))
+ if (apiResponseType.Type == null)
{
- if (type != null && statusCode is StatusCodes.Status200OK or 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))
+ if (type != null && (statusCode == StatusCodes.Status200OK || statusCode == StatusCodes.Status201Created))
{
- // 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;
+ // Allow setting the response type from the return type of the method if it has
+ // not been set explicitly by the method.
+ apiResponseType.Type = type;
+ }
}
- // 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();
+ if (metadata.ContentTypes != null)
{
- var attributeContentTypes = new MediaTypeCollection();
- metadataAttribute.SetContentTypes(attributeContentTypes);
- CalculateResponseFormatForType(apiResponseType, attributeContentTypes,
- responseTypeMetadataProviders, modelMetadataProvider);
+ foreach (var contentType in metadata.ContentTypes)
+ {
+ attributeContentTypes.Add(contentType);
+ }
}
- if (apiResponseType.Type != null) results[apiResponseType.StatusCode] = apiResponseType;
+ CalculateResponseFormatForType(apiResponseType, attributeContentTypes, responseTypeMetadataProviders, modelMetadataProvider);
+
+ if (apiResponseType.Type != null)
+ {
+ results[apiResponseType.StatusCode] = apiResponseType;
+ }
}
- return results.Values.ToList();
+ return results;
}
// Shared with EndpointMetadataApiDescriptionProvider
- internal static void CalculateResponseFormatForType(ApiResponseType apiResponse,
- MediaTypeCollection declaredContentTypes,
- IEnumerable<IApiResponseTypeMetadataProvider>? responseTypeMetadataProviders,
- IModelMetadataProvider? modelMetadataProvider)
+ 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;
+ 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.
@@ -196,7 +297,10 @@ public class ApiResponseTypeProvider
// 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;
+ if (responseType == null || responseType == typeof(void))
+ {
+ return;
+ }
apiResponse.ModelMetadata = modelMetadataProvider?.GetMetadataForType(responseType);
@@ -205,29 +309,37 @@ public class ApiResponseTypeProvider
var isSupportedContentType = false;
if (responseTypeMetadataProviders != null)
+ {
foreach (var responseTypeMetadataProvider in responseTypeMetadataProviders)
{
var formatterSupportedContentTypes = responseTypeMetadataProvider.GetSupportedContentTypes(
contentType,
responseType);
- if (formatterSupportedContentTypes == null) continue;
+ if (formatterSupportedContentTypes == null)
+ {
+ continue;
+ }
isSupportedContentType = true;
foreach (var formatterSupportedContentType in formatterSupportedContentTypes)
+ {
apiResponse.ApiResponseFormats.Add(new ApiResponseFormat {
Formatter = (IOutputFormatter)responseTypeMetadataProvider,
- MediaType = formatterSupportedContentType
+ MediaType = formatterSupportedContentType,
});
+ }
}
+ }
-
- if (!isSupportedContentType)
+ 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
+ MediaType = contentType,
});
+ }
}
}
@@ -237,18 +349,25 @@ public class ApiResponseTypeProvider
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<>)))
+ (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
+ // If the method is declared to return IActionResult, IResult or a derived class, that information
// isn't valuable to the formatter.
- if (typeof(IActionResult).IsAssignableFrom(unwrappedType)) return null;
+ if (typeof(IActionResult).IsAssignableFrom(unwrappedType) ||
+ typeof(IResult).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.
@@ -256,7 +375,7 @@ public class ApiResponseTypeProvider
return unwrappedType;
}
- private Type? GetRuntimeReturnType(Type? declaredReturnType)
+ private static 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.
@@ -264,7 +383,17 @@ public class ApiResponseTypeProvider
// 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.
- return declaredReturnType == typeof(object) ? null : declaredReturnType;
+ 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)
@@ -273,9 +402,11 @@ public class ApiResponseTypeProvider
{
var provider = providers[i];
- if (provider is ProducesAttribute { Type: null })
+ 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;
diff --git a/src/Modules/Grand.Module.Api/ApiExplorer/MetadataApiDescriptionProvider.cs b/src/Modules/Grand.Module.Api/ApiExplorer/MetadataApiDescriptionProvider.cs
index 01531d850..2b79de16d 100644
--- a/src/Modules/Grand.Module.Api/ApiExplorer/MetadataApiDescriptionProvider.cs
+++ b/src/Modules/Grand.Module.Api/ApiExplorer/MetadataApiDescriptionProvider.cs
@@ -1,55 +1,39 @@
-//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+//https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.ApiExplorer/src/DefaultApiDescriptionProvider.cs
#nullable enable
using Grand.SharedKernel.Attributes;
-using Grand.SharedKernel.Extensions;
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.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.Options;
using System.Reflection;
-using ApiControllerAttribute = Grand.SharedKernel.Attributes.ApiControllerAttribute;
namespace Grand.Module.Api.ApiExplorer;
public class MetadataApiDescriptionProvider : IApiDescriptionProvider
{
- private readonly IInlineConstraintResolver _constraintResolver;
- private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly MvcOptions _mvcOptions;
private readonly ApiResponseTypeProvider _responseTypeProvider;
private readonly RouteOptions _routeOptions;
+ private readonly IModelMetadataProvider _modelMetadataProvider;
- /// <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;
@@ -65,9 +49,8 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider
foreach (var action in context.Actions.OfType<ControllerActionDescriptor>())
{
- if (!action.ControllerTypeInfo.GetCustomAttributes<ApiControllerAttribute>(true)
- .Any())
- continue;
+ var apiGroup = action.ControllerTypeInfo.GetCustomAttributes<ApiGroupAttribute>().FirstOrDefault();
+ if (apiGroup == null) continue;
if (action.MethodInfo.GetCustomAttributes<IgnoreApiAttribute>(true).Any())
continue;
@@ -75,7 +58,11 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider
if (action.AttributeRouteInfo is { SuppressPathMatching: true }) continue;
var httpMethods = GetHttpMethods(action);
- foreach (var httpMethod in httpMethods) context.Results.Add(CreateApiDescription(action, httpMethod, "v2"));
+ foreach (var httpMethod in httpMethods)
+ {
+ var apiDescription = CreateApiDescription(action, httpMethod, apiGroup.GroupName);
+ context.Results.Add(apiDescription);
+ };
}
}
@@ -90,232 +77,124 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider
string groupName)
{
var parsedTemplate = ParseTemplate(action);
- var path = GetRelativePath(action, parsedTemplate);
var apiDescription = new ApiDescription {
ActionDescriptor = action,
GroupName = groupName,
HttpMethod = httpMethod,
- RelativePath = path
+ RelativePath = GetRelativePath(action, parsedTemplate)
};
- var templateParameters = parsedTemplate?.Parameters.ToList() ?? [];
-
- var parameterContext = new ApiParameterContext(_modelMetadataProvider, action, templateParameters);
- foreach (var parameter in GetParameters(parameterContext,
- httpMethod.Equals("GET", StringComparison.CurrentCultureIgnoreCase)))
- 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)
+ foreach (var apiResponseType in apiResponseTypes)
{
- 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
- });
- }
+ apiDescription.SupportedResponseTypes.Add(apiResponseType);
}
+ if (httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
+ {
+ AddGetParameters(apiDescription, action);
+ }
+ if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
+ {
+ AddPostParameters(apiDescription, action);
+ }
return apiDescription;
}
-
- private IList<ApiParameterDescription> GetParameters(ApiParameterContext context, bool httpGet)
+ private void AddGetParameters(ApiDescription apiDescription, ControllerActionDescriptor action)
{
- // First, get parameters from the model-binding/parameter-binding side of the world.
- foreach (var actionParameter in context.ActionDescriptor.Parameters)
+ var actionParameters = apiDescription.ActionDescriptor.Parameters;
+ foreach (var param in actionParameters)
{
- 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 (!httpGet &&
- actionParameter.BindingInfo == null &&
- !CommonHelper.IsSimpleType(actionParameter.ParameterType))
- {
- var bindingContext = new ApiParameterDescriptionContext(
- metadata,
- new BindingInfo {
- BindingSource = new BindingSource("Body", "Body", true, true)
- },
- actionParameter.Name);
- visitor.WalkParameter(bindingContext);
- }
- else
+ var paramType = param.ParameterType;
+ if (!IsSimpleType(paramType))
{
- var bindingContext = new ApiParameterDescriptionContext(
- metadata,
- actionParameter.BindingInfo,
- actionParameter.Name);
- visitor.WalkParameter(bindingContext);
- }
- }
-
- foreach (var actionParameter in context.ActionDescriptor.BoundProperties)
- {
- var visitor = new PseudoModelBindingVisitor(context, actionParameter);
- var modelMetadata = context.MetadataProvider.GetMetadataForProperty(
- context.ActionDescriptor.ControllerTypeInfo.AsType(),
- actionParameter.Name);
+ var properties = paramType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
- var bindingContext = new ApiParameterDescriptionContext(
- modelMetadata,
- actionParameter.BindingInfo,
- 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);
+ foreach (var property in properties)
+ {
+ if (property.GetCustomAttribute<IgnoreApiAttribute>() != null)
+ continue;
+
+ apiDescription.ParameterDescriptions.Add(new ApiParameterDescription {
+ Name = property.Name,
+ ModelMetadata = _modelMetadataProvider.GetMetadataForType(property.PropertyType),
+ Source = BindingSource.Query,
+ Type = property.PropertyType
+ });
+ }
}
else
- {
- if (context.Results[i].ModelMetadata is DefaultModelMetadata metadata &&
- metadata.Attributes.Attributes.OfType<IgnoreApiUrlAttribute>().Any())
- 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;
+ apiDescription.ParameterDescriptions.Add(new ApiParameterDescription {
+ Name = param.Name,
+ ModelMetadata = GetModel(param),
+ Source = BindingSource.Query,
+ Type = param.ParameterType
+ });
+ }
}
- private void ProcessRouteParameters(ApiParameterContext context)
+ private void AddPostParameters(ApiDescription apiDescription, ControllerActionDescriptor action)
{
- 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
+ var actionParameters = apiDescription.ActionDescriptor.Parameters;
+ foreach (var param in actionParameters)
+ {
+ apiDescription.ParameterDescriptions.Add(new ApiParameterDescription {
+ Name = param.Name,
+ ModelMetadata = GetModel(param),
+ Source = BindingSource.Body,
+ Type = param.ParameterType
});
+ }
}
-
- internal static void ProcessIsRequired(ApiParameterContext context, MvcOptions mvcOptions)
+ private ModelMetadata GetModel(ParameterDescriptor param)
{
- foreach (var parameter in context.Results)
+ ModelMetadata metadata;
+ if (param is ControllerParameterDescriptor controllerParameterDescriptor &&
+ _modelMetadataProvider is ModelMetadataProvider provider)
{
- 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 is { IsBindingRequired: true }) parameter.IsRequired = true;
-
- if (parameter.Source == BindingSource.Path && parameter.RouteInfo is { IsOptional: false })
- parameter.IsRequired = true;
+ metadata = provider.GetMetadataForParameter(controllerParameterDescriptor.ParameterInfo);
+ }
+ else
+ {
+ metadata = _modelMetadataProvider.GetMetadataForType(param.ParameterType);
}
- }
- 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;
- }
- }*/
+ return metadata;
}
-
- private ApiParameterRouteInfo CreateRouteInfo(TemplatePart routeParameter)
+ private static bool IsSimpleType(Type type)
{
- var constraints = new List<IRouteConstraint>();
- 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
- };
+ return type.IsPrimitive
+ || type.IsEnum
+ || type == typeof(string)
+ || type == typeof(decimal)
+ || type == typeof(DateTime)
+ || type == typeof(DateTimeOffset)
+ || type == typeof(Guid)
+ || type == typeof(TimeSpan);
}
+
private static IEnumerable<string> GetHttpMethods(ControllerActionDescriptor action)
{
- return action.ActionConstraints is { Count: > 0 }
- ? action.ActionConstraints.OfType<HttpMethodActionConstraint>().SelectMany(c => c.HttpMethods)
- : [string.Empty];
+ if (action.ActionConstraints != null && action.ActionConstraints.Count > 0)
+ {
+ return action.ActionConstraints.OfType<HttpMethodActionConstraint>().SelectMany(c => c.HttpMethods);
+ }
+ else
+ {
+ return [];
+ }
}
private static RouteTemplate? ParseTemplate(ControllerActionDescriptor action)
{
- return action.AttributeRouteInfo?.Template != null
- ? TemplateParser.Parse(action.AttributeRouteInfo.Template)
- : null;
+ if (action.AttributeRouteInfo?.Template != null)
+ {
+ return TemplateParser.Parse(action.AttributeRouteInfo.Template);
+ }
+
+ return null;
}
private string? GetRelativePath(ControllerActionDescriptor action, RouteTemplate? parsedTemplate)
@@ -337,247 +216,4 @@ public class MetadataApiDescriptionProvider : IApiDescriptionProvider
return string.Join("/", segments);
}
-
- private IReadOnlyList<ApiRequestFormat> GetSupportedFormats(MediaTypeCollection contentTypes, Type type)
- {
- if (contentTypes.Count == 0) contentTypes = ["application/json"];
-
- var results = new List<ApiRequestFormat>();
- foreach (var contentType in contentTypes)
- foreach (var formatter in _mvcOptions.InputFormatters.OfType<SystemTextJsonInputFormatter>())
- 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)
- {
- // 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 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;
- }
-
- public ModelMetadata ModelMetadata { get; }
-
- public string? BinderModelName { get; }
-
- public BindingSource? BindingSource { get; }
-
- public string? PropertyName { get; }
-
- public BindingInfo? BindingInfo { get; }
- }
-
- 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, 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([], propertyMetadata);
-
- var propertyContext = new ApiParameterDescriptionContext(
- propertyMetadata,
- bindingInfo,
- 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 file
diff --git a/src/Modules/Grand.Module.Api/Attributes/EnableQueryAttribute.cs b/src/Modules/Grand.Module.Api/Attributes/EnableQueryAttribute.cs
new file mode 100644
index 000000000..b77a19ca6
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Attributes/EnableQueryAttribute.cs
@@ -0,0 +1,48 @@
+using Microsoft.AspNetCore.Mvc.Filters;
+using Microsoft.AspNetCore.Mvc;
+using System.Linq.Dynamic.Core;
+using Microsoft.AspNetCore.Http;
+using Grand.Module.Api.Constants;
+
+namespace Grand.Module.Api.Attributes;
+
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
+public class EnableQueryAttribute : ActionFilterAttribute
+{
+ public override void OnActionExecuted(ActionExecutedContext context)
+ {
+ if (context.Result is not ObjectResult result || result.Value == null)
+ return;
+
+ if (result.Value is IQueryable queryable)
+ {
+ queryable = ApplyQueryOptions(queryable, context.HttpContext.Request.Query, context.HttpContext.Response);
+ result.Value = queryable;
+ }
+ }
+
+ private IQueryable ApplyQueryOptions(IQueryable queryable, IQueryCollection query, HttpResponse response)
+ {
+ if (query.TryGetValue("$filter", out var filter))
+ queryable = queryable.Where(filter.ToString());
+
+ if (query.TryGetValue("$orderby", out var orderBy))
+ queryable = queryable.OrderBy(orderBy.ToString());
+
+ if (query.TryGetValue("$select", out var select))
+ queryable = queryable.Select($"new({select})");
+
+ if (query.TryGetValue("$skip", out var skipValue) && int.TryParse(skipValue, out var skip))
+ queryable = queryable.Skip(skip);
+
+ if (query.TryGetValue("$top", out var topValue) && int.TryParse(topValue, out var top))
+ {
+ top = Math.Min(top, Configurations.MaxLimit);
+ queryable = queryable.Take(top);
+ }
+ else
+ queryable = queryable.Take(Configurations.MaxLimit);
+
+ return queryable;
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/ModelValidationAttribute.cs b/src/Modules/Grand.Module.Api/Attributes/ModelValidationAttribute.cs
similarity index 88%
rename from src/Modules/Grand.Module.Api/Infrastructure/ModelValidationAttribute.cs
rename to src/Modules/Grand.Module.Api/Attributes/ModelValidationAttribute.cs
index 57d3f8d63..adc9993b8 100644
--- a/src/Modules/Grand.Module.Api/Infrastructure/ModelValidationAttribute.cs
+++ b/src/Modules/Grand.Module.Api/Attributes/ModelValidationAttribute.cs
@@ -1,7 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
-namespace Grand.Module.Api.Infrastructure;
+namespace Grand.Module.Api.Attributes;
public class ModelValidationAttribute : ActionFilterAttribute
{
diff --git a/src/Modules/Grand.Module.Api/Constants/Configurations.cs b/src/Modules/Grand.Module.Api/Constants/Configurations.cs
index 7ba4e765e..99aca0b0a 100644
--- a/src/Modules/Grand.Module.Api/Constants/Configurations.cs
+++ b/src/Modules/Grand.Module.Api/Constants/Configurations.cs
@@ -2,8 +2,7 @@
public static class Configurations
{
- public const string ODataRoutePrefix = "odata";
- public const string ODataModelBuilderNamespace = "Default";
+ public const string RestRoutePrefix = "api";
public const string CorsPolicyName = "CorsPolicy";
public const int MaxLimit = 100;
}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Controllers/BaseODataController.cs b/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs
similarity index 58%
rename from src/Modules/Grand.Module.Api/Controllers/BaseODataController.cs
rename to src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs
index 5fd18a3b3..2816e836b 100644
--- a/src/Modules/Grand.Module.Api/Controllers/BaseODataController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs
@@ -1,18 +1,19 @@
-using Grand.Module.Api.Filters;
-using Grand.Module.Api.Infrastructure;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Constants;
+using Grand.Module.Api.Filters;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Routing.Attributes;
-using Microsoft.AspNetCore.OData.Routing.Controllers;
namespace Grand.Module.Api.Controllers;
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
-[ODataRouteComponent]
[AuthorizeApiAdmin]
[ServiceFilter(typeof(ModelValidationAttribute))]
-public abstract class BaseODataController : ODataController
+[Route($"{Configurations.RestRoutePrefix}/[controller]")]
+[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
+[Produces("application/json")]
+public abstract class BaseApiController : ControllerBase
{
public override ForbidResult Forbid()
{
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/BrandController.cs b/src/Modules/Grand.Module.Api/Controllers/BrandController.cs
similarity index 73%
rename from src/Modules/Grand.Module.Api/Controllers/OData/BrandController.cs
rename to src/Modules/Grand.Module.Api/Controllers/BrandController.cs
index 402bc63df..17ad015ad 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/BrandController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/BrandController.cs
@@ -7,16 +7,14 @@ using Grand.Domain.Catalog;
using MediatR;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Microsoft.AspNetCore.Http;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Brand")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class BrandController : BaseODataController
+public class BrandController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -27,11 +25,12 @@ public class BrandController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entities from Brand", OperationId = "GetBrands")]
+ [EndpointDescription("Get entities from Brand")]
+ [EndpointName("GetBrands")]
[HttpGet]
- [MongoEnableQuery]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<BrandDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();
@@ -39,11 +38,12 @@ public class BrandController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<BrandDto, Brand>()));
}
- [SwaggerOperation("Get entity from Brand by key", OperationId = "GetBrandById")]
+ [EndpointDescription("Get entity from Brand by key")]
+ [EndpointName("GetBrandById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(BrandDto))]
public async Task<IActionResult> GetById([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();
@@ -54,10 +54,11 @@ public class BrandController : BaseODataController
return Ok(brand.FirstOrDefault());
}
- [SwaggerOperation("Add new entity to Brand", OperationId = "InsertBrand")]
+ [EndpointDescription("Add new entity to Brand")]
+ [EndpointName("InsertBrand")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(BrandDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] BrandDto model)
{
@@ -67,29 +68,34 @@ public class BrandController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Brand", OperationId = "UpdateBrand")]
+ [EndpointDescription("Update entity in Brand")]
+ [EndpointName("UpdateBrand")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(BrandDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Put([FromBody] BrandDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();
- var brand = await _mediator.Send(new GetGenericQuery<BrandDto, Brand>(model.Id));
- if (!brand.Any()) return NotFound();
-
model = await _mediator.Send(new UpdateBrandCommand { Model = model });
return Ok(model);
}
- [SwaggerOperation("Partially update entity in Brand", OperationId = "PartiallyUpdateBrand")]
+ [EndpointDescription("Partially update entity in Brand")]
+ [EndpointName("PartiallyUpdateBrand")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
+
+ ///sample
+ ///{
+ /// "op": "replace",
+ /// "path": "/name",
+ /// "value": "new name"
+ ///}
public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<BrandDto> model)
{
if (string.IsNullOrEmpty(key))
@@ -106,12 +112,13 @@ public class BrandController : BaseODataController
return Ok();
}
- [SwaggerOperation("Delete entity in Brand", OperationId = "DeleteBrand")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in Brand")]
+ [EndpointName("DeleteBrand")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Brands)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/BrandLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs
similarity index 62%
rename from src/Modules/Grand.Module.Api/Controllers/OData/BrandLayoutController.cs
rename to src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs
index f3a84471f..b71a27321 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/BrandLayoutController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs
@@ -5,17 +5,14 @@ using Grand.Domain.Permissions;
using Grand.Domain.Catalog;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/BrandLayout")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class BrandLayoutController : BaseODataController
+public class BrandLayoutController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,12 +23,13 @@ public class BrandLayoutController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from BrandLayout by key", OperationId = "GetBrandLayoutById")]
+ [EndpointDescription("Get entity from BrandLayout by key")]
+ [EndpointName("GetBrandLayoutById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LayoutDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Get(string key)
+ public async Task<IActionResult> Get([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();
@@ -41,11 +39,12 @@ public class BrandLayoutController : BaseODataController
return Ok(layout.FirstOrDefault());
}
- [SwaggerOperation("Get entities from BrandLayout", OperationId = "GetBrandLayouts")]
+ [EndpointDescription("Get entities from BrandLayout")]
+ [EndpointName("GetBrandLayouts")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<LayoutDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CategoryController.cs b/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs
similarity index 72%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CategoryController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CategoryController.cs
index fe9301856..a4789a1ea 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CategoryController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs
@@ -7,17 +7,14 @@ using Grand.Domain.Catalog;
using MediatR;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Category")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CategoryController : BaseODataController
+public class CategoryController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -30,10 +27,11 @@ public class CategoryController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Category by key", OperationId = "GetCategoryById")]
+ [EndpointDescription("Get entity from Category by key")]
+ [EndpointName("GetCategoryById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CategoryDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -45,11 +43,12 @@ public class CategoryController : BaseODataController
return Ok(category.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Category", OperationId = "GetCategories")]
+ [EndpointDescription("Get entities from Category")]
+ [EndpointName("GetCategories")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CategoryDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();
@@ -57,10 +56,11 @@ public class CategoryController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<CategoryDto, Category>()));
}
- [SwaggerOperation("Add new entity to Category", OperationId = "InsertCategory")]
+ [EndpointDescription("Add new entity to Category")]
+ [EndpointName("InsertCategory")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CategoryDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] CategoryDto model)
{
@@ -70,24 +70,22 @@ public class CategoryController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Category", OperationId = "UpdateCategory")]
+ [EndpointDescription("Update entity in Category")]
+ [EndpointName("UpdateCategory")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CategoryDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Put([FromBody] CategoryDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();
- var category = await _mediator.Send(new GetGenericQuery<CategoryDto, Category>(model.Id));
- if (!category.Any()) return NotFound();
-
model = await _mediator.Send(new UpdateCategoryCommand { Model = model });
return Ok(model);
}
- [SwaggerOperation("Update entity in Category (delta)", OperationId = "UpdateCategoryPatch")]
+ [EndpointDescription("Update entity in Category (delta)")]
+ [EndpointName("UpdateCategoryPatch")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
@@ -109,12 +107,13 @@ public class CategoryController : BaseODataController
return Ok();
}
- [SwaggerOperation("Delete entity from Category", OperationId = "DeleteCategory")]
- [HttpDelete]
+ [EndpointDescription("Delete entity from Category")]
+ [EndpointName("DeleteCategory")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CategoryLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs
similarity index 64%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CategoryLayoutController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs
index ea5d6ce56..5224e5e61 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CategoryLayoutController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs
@@ -5,17 +5,14 @@ using Grand.Domain.Permissions;
using Grand.Domain.Catalog;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/CategoryLayout")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CategoryLayoutController : BaseODataController
+public class CategoryLayoutController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -28,10 +25,11 @@ public class CategoryLayoutController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from CategoryLayout by key", OperationId = "GetCategoryLayoutById")]
+ [EndpointDescription("Get entity from CategoryLayout by key")]
+ [EndpointName("GetCategoryLayoutById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LayoutDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -43,11 +41,12 @@ public class CategoryLayoutController : BaseODataController
return Ok(layout.FirstOrDefault());
}
- [SwaggerOperation("Get entities from CategoryLayout", OperationId = "GetCategoryLayout")]
+ [EndpointDescription("Get entities from CategoryLayout")]
+ [EndpointName("GetCategoryLayout")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<LayoutDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CollectionController.cs b/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs
similarity index 71%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CollectionController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CollectionController.cs
index c5ece8cfb..6ad6cea19 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CollectionController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs
@@ -1,23 +1,20 @@
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Catalog;
using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
using Grand.Module.Api.Commands.Models.Catalog;
-using Grand.Module.Api.Constants;
using Grand.Module.Api.DTOs.Catalog;
using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Collection")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CollectionController : BaseODataController
+public class CollectionController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -28,10 +25,11 @@ public class CollectionController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Collection by key", OperationId = "GetCollectionById")]
+ [EndpointDescription("Get entity from Collection by key")]
+ [EndpointName("GetCollectionById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CollectionDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -43,11 +41,12 @@ public class CollectionController : BaseODataController
return Ok(collection);
}
- [SwaggerOperation("Get entities from Collection", OperationId = "GetCollections")]
+ [EndpointDescription("Get entities from Collection")]
+ [EndpointName("GetCollections")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CollectionDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();
@@ -55,10 +54,11 @@ public class CollectionController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>()));
}
- [SwaggerOperation("Add new entity to Collection", OperationId = "InsertCollection")]
+ [EndpointDescription("Add new entity to Collection")]
+ [EndpointName("InsertCollection")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CollectionDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] CollectionDto model)
{
@@ -68,24 +68,22 @@ public class CollectionController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Collection", OperationId = "UpdateCollection")]
+ [EndpointDescription("Update entity in Collection")]
+ [EndpointName("UpdateCollection")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CollectionDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Put([FromBody] CollectionDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();
- var collection = await _mediator.Send(new GetGenericQuery<CollectionDto, Collection>(model.Id));
- if (!collection.Any()) return NotFound();
-
model = await _mediator.Send(new UpdateCollectionCommand { Model = model });
return Ok(model);
}
- [SwaggerOperation("Partially update entity in Collection", OperationId = "PartiallyUpdateCollection")]
+ [EndpointDescription("Partially update entity in Collection")]
+ [EndpointName("PartiallyUpdateCollection")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
@@ -107,12 +105,13 @@ public class CollectionController : BaseODataController
return Ok();
}
- [SwaggerOperation("Delete entity in Collection", OperationId = "DeleteCollection")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in Collection")]
+ [EndpointName("DeleteCollection")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Collections)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CollectionLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs
similarity index 59%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CollectionLayoutController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs
index 6c32129ee..3a450ca98 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CollectionLayoutController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Common;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/CollectionLayout")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CollectionLayoutController : BaseODataController
+public class CollectionLayoutController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class CollectionLayoutController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from CollectionLayout by key", OperationId = "GetCollectionLayoutById")]
+ [EndpointDescription("Get entity from CollectionLayout by key")]
+ [EndpointName("GetCollectionLayoutById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LayoutDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class CollectionLayoutController : BaseODataController
return Ok(layout.FirstOrDefault());
}
- [SwaggerOperation("Get entities from CollectionLayout", OperationId = "GetCollectionLayouts")]
+ [EndpointDescription("Get entities from CollectionLayout")]
+ [EndpointName("GetCollectionLayouts")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<LayoutDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CountryController.cs b/src/Modules/Grand.Module.Api/Controllers/CountryController.cs
similarity index 66%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CountryController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CountryController.cs
index b4f7f3477..e18adebbe 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CountryController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CountryController.cs
@@ -5,17 +5,14 @@ using Grand.Domain.Permissions;
using Grand.Domain.Directory;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Country")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CountryController : BaseODataController
+public class CountryController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class CountryController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Country by key", OperationId = "GetCountryById")]
+ [EndpointDescription("Get entity from Country by key")]
+ [EndpointName("GetCountryById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountryDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -42,11 +40,12 @@ public class CountryController : BaseODataController
return Ok(country.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Country", OperationId = "GetCountries")]
+ [EndpointDescription("Get entities from Country")]
+ [EndpointName("GetCountries")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CountryDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Countries)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CurrencyController.cs b/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs
similarity index 65%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CurrencyController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs
index c8b08cf59..7f62fdf74 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CurrencyController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs
@@ -5,17 +5,14 @@ using Grand.Domain.Permissions;
using Grand.Domain.Directory;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
using System.Net;
-using Grand.Module.Api.Constants;
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Currency")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CurrencyController : BaseODataController
+public class CurrencyController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class CurrencyController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Currency by key", OperationId = "GetCurrencyById")]
+ [EndpointDescription("Get entity from Currency by key")]
+ [EndpointName("GetCurrencyById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CurrencyDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class CurrencyController : BaseODataController
return Ok(currency.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Currency", OperationId = "GetCurrencies")]
+ [EndpointDescription("Get entities from Currency")]
+ [EndpointName("GetCurrencies")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CurrencyDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Currencies)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CustomerController.cs b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs
similarity index 75%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CustomerController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CustomerController.cs
index 01aa8732a..e0f4d4cfc 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CustomerController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs
@@ -1,22 +1,20 @@
-using Grand.Module.Api.Commands.Models.Customers;
-using Grand.Module.Api.DTOs.Customers;
-using Grand.Module.Api.Queries.Models.Customers;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Domain.Permissions;
using Grand.Business.Core.Utilities.Customers;
using Grand.Domain.Customers;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Commands.Models.Customers;
+using Grand.Module.Api.DTOs.Customers;
+using Grand.Module.Api.Queries.Models.Customers;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Customer")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CustomerController : BaseODataController
+public class CustomerController : BaseApiController
{
private readonly ICustomerManagerService _customerManagerService;
@@ -36,10 +34,11 @@ public class CustomerController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Customer by email", OperationId = "GetCustomerByEmail")]
+ [EndpointDescription("Get entity from Customer by email")]
+ [EndpointName("GetCustomerByEmail")]
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string email)
{
@@ -51,10 +50,11 @@ public class CustomerController : BaseODataController
return Ok(customer);
}
- [SwaggerOperation("Add new entity to Customer", OperationId = "InsertCustomer")]
+ [EndpointDescription("Add new entity to Customer")]
+ [EndpointName("InsertCustomer")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] CustomerDto model)
{
@@ -64,10 +64,11 @@ public class CustomerController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Customer", OperationId = "UpdateCustomer")]
+ [EndpointDescription("Update entity in Customer")]
+ [EndpointName("UpdateCustomer")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Put([FromBody] CustomerDto model)
{
@@ -77,8 +78,9 @@ public class CustomerController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Delete entity from Customer", OperationId = "DeleteCustomer")]
- [HttpDelete]
+ [EndpointDescription("Delete entity from Customer")]
+ [EndpointName("DeleteCustomer")]
+ [HttpDelete("{email}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
@@ -94,11 +96,12 @@ public class CustomerController : BaseODataController
return Ok();
}
- //odata/Customer/email/AddAddress
- [SwaggerOperation("Invoke action AddAddress", OperationId = "AddAddress")]
- [HttpPost("/{email}/AddAddress")]
+ //api/Customer/email/AddAddress
+ [EndpointDescription("Invoke action AddAddress")]
+ [EndpointName("AddAddress")]
+ [HttpPost("{email}/AddAddress")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AddressDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> AddAddress([FromRoute] string email, [FromBody] AddressDto address)
@@ -112,11 +115,12 @@ public class CustomerController : BaseODataController
return Ok(address);
}
- //odata/Customer/email/UpdateAddress
- [SwaggerOperation("Invoke action UpdateAddress", OperationId = "UpdateAddress")]
- [HttpPost("/{email}/UpdateAddress")]
+ //api/Customer/email/UpdateAddress
+ [EndpointDescription("Invoke action UpdateAddress")]
+ [EndpointName("UpdateAddress")]
+ [HttpPost("{email}/UpdateAddress")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AddressDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> UpdateAddress([FromRoute] string email, [FromBody] AddressDto address)
@@ -131,10 +135,11 @@ public class CustomerController : BaseODataController
return Ok(address);
}
- //odata/Customer/email/DeleteAddress
+ //api/Customer/email/DeleteAddress
//body: { "addressId": "xxx" }
- [SwaggerOperation("Invoke action DeleteAddress", OperationId = "DeleteAddress")]
- [HttpPost("/{email}/DeleteAddress")]
+ [EndpointDescription("Invoke action DeleteAddress")]
+ [EndpointName("DeleteAddress")]
+ [HttpPost("{email}/DeleteAddress")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
@@ -155,10 +160,11 @@ public class CustomerController : BaseODataController
return Ok(true);
}
- //odata/Customer/email/SetPassword
+ //api/Customer/email/SetPassword
//body: { "password": "123456" }
- [SwaggerOperation("Invoke action SetPassword", OperationId = "SetPassword")]
- [HttpPost("/{email}/SetPassword")]
+ [EndpointDescription("Invoke action SetPassword")]
+ [EndpointName("SetPassword")]
+ [HttpPost("{email}/SetPassword")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
@@ -169,8 +175,7 @@ public class CustomerController : BaseODataController
if (model == null || string.IsNullOrEmpty(model.Password)) return NotFound();
- var changePassRequest =
- new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);
+ var changePassRequest = new ChangePasswordRequest(email, _customerSettings.DefaultPasswordFormat, model.Password);
await _customerManagerService.ChangePassword(changePassRequest);
return Ok(true);
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/CustomerGroupController.cs b/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs
similarity index 70%
rename from src/Modules/Grand.Module.Api/Controllers/OData/CustomerGroupController.cs
rename to src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs
index a240b131f..4c1e94cf4 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/CustomerGroupController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs
@@ -1,23 +1,20 @@
-using Grand.Module.Api.Commands.Models.Customers;
+using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Domain.Customers;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Commands.Models.Customers;
using Grand.Module.Api.DTOs.Customers;
using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
-using Grand.Domain.Customers;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/CustomerGroup")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class CustomerGroupController : BaseODataController
+public class CustomerGroupController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -28,10 +25,11 @@ public class CustomerGroupController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from CustomerGroup by key", OperationId = "GetCustomerGroupById")]
+ [EndpointDescription("Get entity from CustomerGroup by key")]
+ [EndpointName("GetCustomerGroupById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerGroupDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -43,11 +41,12 @@ public class CustomerGroupController : BaseODataController
return Ok(customerGroup.FirstOrDefault());
}
- [SwaggerOperation("Get entities from CustomerGroup", OperationId = "GetCustomerGroups")]
+ [EndpointDescription("Get entities from CustomerGroup")]
+ [EndpointName("GetCustomerGroups")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<CustomerGroupDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();
@@ -55,10 +54,11 @@ public class CustomerGroupController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>()));
}
- [SwaggerOperation("Add new entity to CustomerGroup", OperationId = "InsertCustomerGroup")]
+ [EndpointDescription("Add new entity to CustomerGroup")]
+ [EndpointName("InsertCustomerGroup")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerGroupDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] CustomerGroupDto model)
{
@@ -68,19 +68,16 @@ public class CustomerGroupController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in CustomerGroup", OperationId = "UpdateCustomerGroup")]
+ [EndpointDescription("Update entity in CustomerGroup")]
+ [EndpointName("UpdateCustomerGroup")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerGroupDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Put([FromBody] CustomerGroupDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();
- var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(model.Id));
- if (!customerGroup.Any()) return NotFound();
-
if (!model.IsSystem)
{
model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model });
@@ -90,7 +87,8 @@ public class CustomerGroupController : BaseODataController
return BadRequest(ModelState);
}
- [SwaggerOperation("Partially update entity in CustomerGroup", OperationId = "PartiallyUpdateCustomerGroup")]
+ [EndpointDescription("Partially update entity in CustomerGroup")]
+ [EndpointName("PartiallyUpdateCustomerGroup")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
@@ -117,12 +115,13 @@ public class CustomerGroupController : BaseODataController
return BadRequest(ModelState);
}
- [SwaggerOperation("Delete entity in CustomerGroup", OperationId = "DeleteCustomerGroup")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in CustomerGroup")]
+ [EndpointName("DeleteCustomerGroup")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/DeliveryDateController.cs b/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs
similarity index 61%
rename from src/Modules/Grand.Module.Api/Controllers/OData/DeliveryDateController.cs
rename to src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs
index a9621b1ba..2210dcf9f 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/DeliveryDateController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Shipping;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Shipping;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/DeliveryDate")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class DeliveryDateController : BaseODataController
+public class DeliveryDateController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class DeliveryDateController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Delivery Date by key", OperationId = "GetDeliveryDateById")]
+ [EndpointDescription("Get entity from Delivery Date by key")]
+ [EndpointName("GetDeliveryDateById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(DeliveryDateDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class DeliveryDateController : BaseODataController
return Ok(deliverydate.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Delivery Date", OperationId = "GetDeliveryDates")]
+ [EndpointDescription("Get entities from Delivery Date")]
+ [EndpointName("GetDeliveryDates")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<DeliveryDateDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/LanguageController.cs b/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs
similarity index 61%
rename from src/Modules/Grand.Module.Api/Controllers/OData/LanguageController.cs
rename to src/Modules/Grand.Module.Api/Controllers/LanguageController.cs
index 9e1a22fa3..bef60bf34 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/LanguageController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Localization;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Common;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Language")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class LanguageController : BaseODataController
+public class LanguageController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class LanguageController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Languages by key", OperationId = "GetLanguageById")]
+ [EndpointDescription("Get entity from Languages by key")]
+ [EndpointName("GetLanguageById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LanguageDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class LanguageController : BaseODataController
return Ok(language.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Languages", OperationId = "GetLanguages")]
+ [EndpointDescription("Get entities from Languages")]
+ [EndpointName("GetLanguages")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<LanguageDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Languages)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/PickupPointController.cs b/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs
similarity index 60%
rename from src/Modules/Grand.Module.Api/Controllers/OData/PickupPointController.cs
rename to src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs
index 24e59b70c..40aacf355 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/PickupPointController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Shipping;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Shipping;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/PickupPoint")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class PickupPointController : BaseODataController
+public class PickupPointController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class PickupPointController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from PickupPoint by key", OperationId = "GetPickupPointById")]
+ [EndpointDescription("Get entity from PickupPoint by key")]
+ [EndpointName("GetPickupPointById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PickupPointDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class PickupPointController : BaseODataController
return Ok(points.FirstOrDefault());
}
- [SwaggerOperation("Get entities from PickupPoint", OperationId = "GetPickupPoints")]
+ [EndpointDescription("Get entities from PickupPoint")]
+ [EndpointName("GetPickupPoints")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<PickupPointDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/PictureController.cs b/src/Modules/Grand.Module.Api/Controllers/PictureController.cs
similarity index 69%
rename from src/Modules/Grand.Module.Api/Controllers/OData/PictureController.cs
rename to src/Modules/Grand.Module.Api/Controllers/PictureController.cs
index a38639a84..f5ce2e779 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/PictureController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/PictureController.cs
@@ -1,20 +1,18 @@
-using Grand.Module.Api.Commands.Models.Common;
+using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Domain.Media;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Commands.Models.Common;
using Grand.Module.Api.DTOs.Common;
using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
-using Grand.Domain.Media;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Picture")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class PictureController : BaseODataController
+public class PictureController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -25,10 +23,11 @@ public class PictureController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entities from Picture by key", OperationId = "GetPictureById")]
+ [EndpointDescription("Get entities from Picture by key")]
+ [EndpointName("GetPictureById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PictureDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -40,7 +39,8 @@ public class PictureController : BaseODataController
return Ok(picture.FirstOrDefault());
}
- [SwaggerOperation("Add new entity in Picture", OperationId = "InsertPicture")]
+ [EndpointDescription("Add new entity in Picture")]
+ [EndpointName("InsertPicture")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
@@ -53,29 +53,27 @@ public class PictureController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Picture", OperationId = "UpdatePicture")]
+ [EndpointDescription("Update entity in Picture")]
+ [EndpointName("UpdatePicture")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
- [ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Put([FromBody] PictureDto model)
{
- if (!await _permissionService.Authorize(PermissionSystemName.Categories)) return Forbid();
-
- var picture = await _mediator.Send(new GetGenericQuery<PictureDto, Picture>(model.Id));
- if (picture == null || !picture.Any()) return NotFound();
+ if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();
var result = await _mediator.Send(new UpdatePictureCommand { Model = model });
return Ok(result);
}
- [SwaggerOperation("Delete entity in Picture", OperationId = "DeletePicture")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in Picture")]
+ [EndpointName("DeletePicture")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.Pictures)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/ProductAttributeController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs
similarity index 70%
rename from src/Modules/Grand.Module.Api/Controllers/OData/ProductAttributeController.cs
rename to src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs
index 5d295b8f0..ee36334d5 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/ProductAttributeController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs
@@ -1,23 +1,20 @@
-using Grand.Module.Api.Commands.Models.Catalog;
+using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Commands.Models.Catalog;
using Grand.Module.Api.DTOs.Catalog;
using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
-using Grand.Domain.Catalog;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/ProductAttribute")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class ProductAttributeController : BaseODataController
+public class ProductAttributeController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -30,10 +27,11 @@ public class ProductAttributeController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from ProductAttribute by key", OperationId = "GetProductAttributeById")]
+ [EndpointDescription("Get entity from ProductAttribute by key")]
+ [EndpointName("GetProductAttributeById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -45,11 +43,12 @@ public class ProductAttributeController : BaseODataController
return Ok(productAttribute.FirstOrDefault());
}
- [SwaggerOperation("Get entities from ProductAttribute", OperationId = "GetProductAttributes")]
+ [EndpointDescription("Get entities from ProductAttribute")]
+ [EndpointName("GetProductAttributes")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<ProductAttributeDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();
@@ -57,10 +56,11 @@ public class ProductAttributeController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<ProductAttributeDto, ProductAttribute>()));
}
- [SwaggerOperation("Add new entity to ProductAttribute", OperationId = "InsertProductAttribute")]
+ [EndpointDescription("Add new entity to ProductAttribute")]
+ [EndpointName("InsertProductAttribute")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] ProductAttributeDto model)
{
@@ -70,10 +70,11 @@ public class ProductAttributeController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in ProductAttribute", OperationId = "UpdateProductAttribute")]
+ [EndpointDescription("Update entity in ProductAttribute")]
+ [EndpointName("UpdateProductAttribute")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Put([FromBody] ProductAttributeDto model)
{
@@ -83,14 +84,14 @@ public class ProductAttributeController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Partially update entity in ProductAttribute", OperationId = "PartiallyUpdateProductAttribute")]
+ [EndpointDescription("Partially update entity in ProductAttribute")]
+ [EndpointName("PartiallyUpdateProductAttribute")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Patch([FromRoute] string key,
- [FromBody] JsonPatchDocument<ProductAttributeDto> model)
+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<ProductAttributeDto> model)
{
if (string.IsNullOrEmpty(key))
return BadRequest("Key is null or empty");
@@ -106,12 +107,13 @@ public class ProductAttributeController : BaseODataController
return Ok(pa);
}
- [SwaggerOperation("Delete entity from ProductAttribute", OperationId = "DeleteProductAttribute")]
- [HttpDelete]
+ [EndpointDescription("Delete entity from ProductAttribute")]
+ [EndpointName("DeleteProductAttribute")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/ProductController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductController.cs
similarity index 75%
rename from src/Modules/Grand.Module.Api/Controllers/OData/ProductController.cs
rename to src/Modules/Grand.Module.Api/Controllers/ProductController.cs
index de5d76e1d..bc30cc56a 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/ProductController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/ProductController.cs
@@ -1,23 +1,20 @@
-using Grand.Module.Api.Commands.Models.Catalog;
+using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Commands.Models.Catalog;
using Grand.Module.Api.DTOs.Catalog;
using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
-using Grand.Domain.Catalog;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Product")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class ProductController : BaseODataController
+public class ProductController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -30,10 +27,11 @@ public class ProductController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Product by key", OperationId = "GetProductById")]
+ [EndpointDescription("Get entity from Product by key")]
+ [EndpointName("GetProductById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -45,11 +43,12 @@ public class ProductController : BaseODataController
return Ok(product.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Product", OperationId = "GetProducts")]
+ [EndpointDescription("Get entities from Product")]
+ [EndpointName("GetProducts")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<ProductDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -57,10 +56,11 @@ public class ProductController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<ProductDto, Product>()));
}
- [SwaggerOperation("Add new entity to Product", OperationId = "InsertProduct")]
+ [EndpointDescription("Add new entity to Product")]
+ [EndpointName("InsertProduct")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] ProductDto model)
{
@@ -70,10 +70,11 @@ public class ProductController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in Product", OperationId = "UpdateProduct")]
+ [EndpointDescription("Update entity in Product")]
+ [EndpointName("UpdateProduct")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProductDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Put([FromBody] ProductDto model)
{
@@ -83,8 +84,9 @@ public class ProductController : BaseODataController
return Ok();
}
- [SwaggerOperation("Partially update entity in Product", OperationId = "PartiallyUpdateProduct")]
- [HttpPatch]
+ [EndpointDescription("Partially update entity in Product")]
+ [EndpointName("PartiallyUpdateProduct")]
+ [HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
@@ -105,8 +107,9 @@ public class ProductController : BaseODataController
return Ok();
}
- [SwaggerOperation("Delete entity in Product", OperationId = "DeleteProduct")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in Product")]
+ [EndpointName("DeleteProduct")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
@@ -122,10 +125,11 @@ public class ProductController : BaseODataController
return Ok();
}
- //odata/Product/id/UpdateStock
+ //api/Product/id/UpdateStock
//body: { "WarehouseId": "", "Stock": 10 }
- [SwaggerOperation("Invoke action UpdateStock", OperationId = "UpdateStock")]
- [HttpPost("/{key}/UpdateStock")]
+ [EndpointDescription("Invoke action UpdateStock")]
+ [EndpointName("UpdateStock")]
+ [HttpPost("{key}/UpdateStock")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
@@ -139,22 +143,21 @@ public class ProductController : BaseODataController
if (model == null) return BadRequest();
- await _mediator.Send(new UpdateProductStockCommand
- { Product = product.FirstOrDefault(), WarehouseId = model.WarehouseId, Stock = model.Stock });
+ await _mediator.Send(new UpdateProductStockCommand { Product = product.FirstOrDefault(), WarehouseId = model.WarehouseId, Stock = model.Stock });
return Ok(true);
}
#region Product category
- [SwaggerOperation("Invoke action CreateProductCategory", OperationId = "CreateProductCategory")]
- [HttpPost("/{key}/CreateProductCategory")]
+ [EndpointDescription("Invoke action CreateProductCategory")]
+ [EndpointName("CreateProductCategory")]
+ [HttpPost("{key}/CreateProductCategory")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductCategory([FromRoute] string key,
- [FromBody] ProductCategoryDto productCategory)
+ public async Task<IActionResult> CreateProductCategory([FromRoute] string key, [FromBody] ProductCategoryDto productCategory)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -169,22 +172,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductCategoryCommand
- { Product = product.FirstOrDefault(), Model = productCategory });
+ var result = await _mediator.Send(new AddProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductCategory", OperationId = "UpdateProductCategory")]
- [HttpPost("/{key}/UpdateProductCategory")]
+ [EndpointDescription("Invoke action UpdateProductCategory")]
+ [EndpointName("UpdateProductCategory")]
+ [HttpPost("{key}/UpdateProductCategory")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductCategory([FromRoute] string key,
- [FromBody] ProductCategoryDto productCategory)
+ public async Task<IActionResult> UpdateProductCategory([FromRoute] string key, [FromBody] ProductCategoryDto productCategory)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -199,22 +201,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductCategoryCommand
- { Product = product.FirstOrDefault(), Model = productCategory });
+ var result = await _mediator.Send(new UpdateProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductCategory", OperationId = "DeleteProductCategory")]
- [HttpPost("/{key}/DeleteProductCategory")]
+ [EndpointDescription("Invoke action DeleteProductCategory")]
+ [EndpointName("DeleteProductCategory")]
+ [HttpPost("{key}/DeleteProductCategory")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductCategory([FromRoute] string key,
- [FromBody] ProductCategoryDeleteDto model)
+ public async Task<IActionResult> DeleteProductCategory([FromRoute] string key, [FromBody] ProductCategoryDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -231,8 +232,7 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- _ = await _mediator.Send(new DeleteProductCategoryCommand
- { Product = product.FirstOrDefault(), CategoryId = categoryId });
+ _ = await _mediator.Send(new DeleteProductCategoryCommand { Product = product.FirstOrDefault(), CategoryId = categoryId });
return Ok(true);
}
@@ -246,14 +246,14 @@ public class ProductController : BaseODataController
#region Product collection
- [SwaggerOperation("Invoke action CreateProductCollection", OperationId = "CreateProductCollection")]
- [HttpPost("/{key}/CreateProductCollection")]
+ [EndpointDescription("Invoke action CreateProductCollection")]
+ [EndpointName("CreateProductCollection")]
+ [HttpPost("{key}/CreateProductCollection")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductCollection([FromRoute] string key,
- [FromBody] ProductCollectionDto productCollection)
+ public async Task<IActionResult> CreateProductCollection([FromRoute] string key, [FromBody] ProductCollectionDto productCollection)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -262,28 +262,26 @@ public class ProductController : BaseODataController
var product = await _mediator.Send(new GetGenericQuery<ProductDto, Product>(key));
if (!product.Any()) return NotFound();
- var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x =>
- x.CollectionId == productCollection.CollectionId);
+ var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId);
if (pm != null) return BadRequest("Product collection mapping found with the specified CollectionId");
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductCollectionCommand
- { Product = product.FirstOrDefault(), Model = productCollection });
+ var result = await _mediator.Send(new AddProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductCollection", OperationId = "UpdateProductCollection")]
- [HttpPost("/{key}/UpdateProductCollection")]
+ [EndpointDescription("Invoke action UpdateProductCollection")]
+ [EndpointName("UpdateProductCollection")]
+ [HttpPost("{key}/UpdateProductCollection")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductCollection([FromRoute] string key,
- [FromBody] ProductCollectionDto productCollection)
+ public async Task<IActionResult> UpdateProductCollection([FromRoute] string key, [FromBody] ProductCollectionDto productCollection)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -298,22 +296,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductCollectionCommand
- { Product = product.FirstOrDefault(), Model = productCollection });
+ var result = await _mediator.Send(new UpdateProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductCollection", OperationId = "DeleteProductCollection")]
- [HttpPost("/{key}/DeleteProductCollection")]
+ [EndpointDescription("Invoke action DeleteProductCollection")]
+ [EndpointName("DeleteProductCollection")]
+ [HttpPost("{key}/DeleteProductCollection")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductCollection([FromRoute] string key,
- [FromBody] ProductCollectionDeleteDto model)
+ public async Task<IActionResult> DeleteProductCollection([FromRoute] string key, [FromBody] ProductCollectionDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -330,8 +327,7 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- await _mediator.Send(new DeleteProductCollectionCommand
- { Product = product.FirstOrDefault(), CollectionId = collectionId });
+ await _mediator.Send(new DeleteProductCollectionCommand { Product = product.FirstOrDefault(), CollectionId = collectionId });
return Ok(true);
}
@@ -345,14 +341,14 @@ public class ProductController : BaseODataController
#region Product picture
- [SwaggerOperation("Invoke action CreateProductPicture", OperationId = "CreateProductPicture")]
- [HttpPost("/{key}/CreateProductPicture")]
+ [EndpointDescription("Invoke action CreateProductPicture")]
+ [EndpointName("CreateProductPicture")]
+ [HttpPost("{key}/CreateProductPicture")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductPicture([FromRoute] string key,
- [FromBody] ProductPictureDto productPicture)
+ public async Task<IActionResult> CreateProductPicture([FromRoute] string key, [FromBody] ProductPictureDto productPicture)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -366,22 +362,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductPictureCommand
- { Product = product.FirstOrDefault(), Model = productPicture });
+ var result = await _mediator.Send(new AddProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductPicture", OperationId = "UpdateProductPicture")]
- [HttpPost("/{key}/UpdateProductPicture")]
+ [EndpointDescription("Invoke action UpdateProductPicture")]
+ [EndpointName("UpdateProductPicture")]
+ [HttpPost("{key}/UpdateProductPicture")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductPicture([FromRoute] string key,
- [FromBody] ProductPictureDto productPicture)
+ public async Task<IActionResult> UpdateProductPicture([FromRoute] string key, [FromBody] ProductPictureDto productPicture)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -395,22 +390,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductPictureCommand
- { Product = product.FirstOrDefault(), Model = productPicture });
+ var result = await _mediator.Send(new UpdateProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductPicture", OperationId = "DeleteProductPicture")]
- [HttpPost("/{key}/DeleteProductPicture")]
+ [EndpointDescription("Invoke action DeleteProductPicture")]
+ [EndpointName("DeleteProductPicture")]
+ [HttpPost("{key}/DeleteProductPicture")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductPicture([FromRoute] string key,
- [FromBody] ProductPictureDeleteDto model)
+ public async Task<IActionResult> DeleteProductPicture([FromRoute] string key, [FromBody] ProductPictureDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -427,8 +421,7 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new DeleteProductPictureCommand
- { Product = product.FirstOrDefault(), PictureId = pictureId });
+ var result = await _mediator.Send(new DeleteProductPictureCommand { Product = product.FirstOrDefault(), PictureId = pictureId });
return Ok(result);
}
@@ -442,14 +435,14 @@ public class ProductController : BaseODataController
#region Product specification
- [SwaggerOperation("Invoke action CreateProductSpecification", OperationId = "CreateProductSpecification")]
- [HttpPost("/{key}/CreateProductSpecification")]
+ [EndpointDescription("Invoke action CreateProductSpecification")]
+ [EndpointName("CreateProductSpecification")]
+ [HttpPost("{key}/CreateProductSpecification")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductSpecification([FromRoute] string key,
- [FromBody] ProductSpecificationAttributeDto productSpecification)
+ public async Task<IActionResult> CreateProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDto productSpecification)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -464,22 +457,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductSpecificationCommand
- { Product = product.FirstOrDefault(), Model = productSpecification });
+ var result = await _mediator.Send(new AddProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductSpecification", OperationId = "UpdateProductSpecification")]
- [HttpPost("/{key}/UpdateProductSpecification")]
+ [EndpointDescription("Invoke action UpdateProductSpecification")]
+ [EndpointName("UpdateProductSpecification")]
+ [HttpPost("{key}/UpdateProductSpecification")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductSpecification([FromRoute] string key,
- [FromBody] ProductSpecificationAttributeDto productSpecification)
+ public async Task<IActionResult> UpdateProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDto productSpecification)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -494,22 +486,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductSpecificationCommand
- { Product = product.FirstOrDefault(), Model = productSpecification });
+ var result = await _mediator.Send(new UpdateProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductSpecification", OperationId = "DeleteProductSpecification")]
- [HttpPost("/{key}/DeleteProductSpecification")]
+ [EndpointDescription("Invoke action DeleteProductSpecification")]
+ [EndpointName("DeleteProductSpecification")]
+ [HttpPost("{key}/DeleteProductSpecification")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductSpecification([FromRoute] string key,
- [FromBody] ProductSpecificationAttributeDeleteDto model)
+ public async Task<IActionResult> DeleteProductSpecification([FromRoute] string key, [FromBody] ProductSpecificationAttributeDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -527,8 +518,7 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new DeleteProductSpecificationCommand
- { Product = product.FirstOrDefault(), Id = specificationId });
+ var result = await _mediator.Send(new DeleteProductSpecificationCommand { Product = product.FirstOrDefault(), Id = specificationId });
return Ok(result);
}
@@ -542,14 +532,14 @@ public class ProductController : BaseODataController
#region Product tierprice
- [SwaggerOperation("Invoke action CreateProductTierPrice", OperationId = "CreateProductTierPrice")]
- [HttpPost("/{key}/CreateProductTierPrice")]
+ [EndpointDescription("Invoke action CreateProductTierPrice")]
+ [EndpointName("CreateProductTierPrice")]
+ [HttpPost("{key}/CreateProductTierPrice")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductTierPrice([FromRoute] string key,
- [FromBody] ProductTierPriceDto productTierPrice)
+ public async Task<IActionResult> CreateProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDto productTierPrice)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -563,22 +553,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductTierPriceCommand
- { Product = product.FirstOrDefault(), Model = productTierPrice });
+ var result = await _mediator.Send(new AddProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductTierPrice", OperationId = "UpdateProductTierPrice")]
- [HttpPost("/{key}/UpdateProductTierPrice")]
+ [EndpointDescription("Invoke action UpdateProductTierPrice")]
+ [EndpointName("UpdateProductTierPrice")]
+ [HttpPost("{key}/UpdateProductTierPrice")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductTierPrice([FromRoute] string key,
- [FromBody] ProductTierPriceDto productTierPrice)
+ public async Task<IActionResult> UpdateProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDto productTierPrice)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -592,22 +581,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductTierPriceCommand
- { Product = product.FirstOrDefault(), Model = productTierPrice });
+ var result = await _mediator.Send(new UpdateProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductTierPrice", OperationId = "DeleteProductTierPrice")]
- [HttpPost("/{key}/DeleteProductTierPrice")]
+ [EndpointDescription("Invoke action DeleteProductTierPrice")]
+ [EndpointName("DeleteProductTierPrice")]
+ [HttpPost("{key}/DeleteProductTierPrice")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductTierPrice([FromRoute] string key,
- [FromBody] ProductTierPriceDeleteDto model)
+ public async Task<IActionResult> DeleteProductTierPrice([FromRoute] string key, [FromBody] ProductTierPriceDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -624,8 +612,7 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new DeleteProductTierPriceCommand
- { Product = product.FirstOrDefault(), Id = tierPriceId });
+ var result = await _mediator.Send(new DeleteProductTierPriceCommand { Product = product.FirstOrDefault(), Id = tierPriceId });
return Ok(result);
}
@@ -639,14 +626,14 @@ public class ProductController : BaseODataController
#region Product attribute mapping
- [SwaggerOperation("Invoke action CreateProductAttributeMapping", OperationId = "CreateProductAttributeMapping")]
- [HttpPost("/{key}/CreateProductAttributeMapping")]
+ [EndpointDescription("Invoke action CreateProductAttributeMapping")]
+ [EndpointName("CreateProductAttributeMapping")]
+ [HttpPost("{key}/CreateProductAttributeMapping")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> CreateProductAttributeMapping([FromRoute] string key,
- [FromBody] ProductAttributeMappingDto productAttributeMapping)
+ public async Task<IActionResult> CreateProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDto productAttributeMapping)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -661,22 +648,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new AddProductAttributeMappingCommand
- { Product = product.FirstOrDefault(), Model = productAttributeMapping });
+ var result = await _mediator.Send(new AddProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action UpdateProductAttributeMapping", OperationId = "UpdateProductAttributeMapping")]
- [HttpPost("/{key}/UpdateProductAttributeMapping")]
+ [EndpointDescription("Invoke action UpdateProductAttributeMapping")]
+ [EndpointName("UpdateProductAttributeMapping")]
+ [HttpPost("{key}/UpdateProductAttributeMapping")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> UpdateProductAttributeMapping([FromRoute] string key,
- [FromBody] ProductAttributeMappingDto productAttributeMapping)
+ public async Task<IActionResult> UpdateProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDto productAttributeMapping)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -691,22 +677,21 @@ public class ProductController : BaseODataController
if (ModelState.IsValid)
{
- var result = await _mediator.Send(new UpdateProductAttributeMappingCommand
- { Product = product.FirstOrDefault(), Model = productAttributeMapping });
+ var result = await _mediator.Send(new UpdateProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping });
return Ok(result);
}
return BadRequest(ModelState);
}
- [SwaggerOperation("Invoke action DeleteProductAttributeMapping", OperationId = "DeleteProductAttributeMapping")]
- [HttpPost("/{key}/DeleteProductAttributeMapping")]
+ [EndpointDescription("Invoke action DeleteProductAttributeMapping")]
+ [EndpointName("DeleteProductAttributeMapping")]
+ [HttpPost("{key}/DeleteProductAttributeMapping")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> DeleteProductAttributeMapping([FromRoute] string key,
- [FromBody] ProductAttributeMappingDeleteDto model)
+ public async Task<IActionResult> DeleteProductAttributeMapping([FromRoute] string key, [FromBody] ProductAttributeMappingDeleteDto model)
{
if (!await _permissionService.Authorize(PermissionSystemName.Products)) return Forbid();
@@ -723,8 +708,7 @@ public class ProductController : BaseODataController
if (!ModelState.IsValid) return BadRequest(ModelState);
- var result = await _mediator.Send(new DeleteProductAttributeMappingCommand
- { Product = product.FirstOrDefault(), Model = pam });
+ var result = await _mediator.Send(new DeleteProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = pam });
return Ok(result);
}
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/ProductLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs
similarity index 64%
rename from src/Modules/Grand.Module.Api/Controllers/OData/ProductLayoutController.cs
rename to src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs
index b3c277949..c71dd9d3b 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/ProductLayoutController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs
@@ -1,21 +1,21 @@
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Constants;
+using Grand.Module.Api.DTOs.Common;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/ProductLayout")]
+[Route($"{Configurations.RestRoutePrefix}/ProductLayout")]
[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class ProductLayoutController : BaseODataController
+public class ProductLayoutController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +26,11 @@ public class ProductLayoutController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from ProductLayout by key", OperationId = "GetProductLayoutById")]
+ [EndpointDescription("Get entity from ProductLayout by key")]
+ [EndpointName("GetProductLayoutById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LayoutDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +42,12 @@ public class ProductLayoutController : BaseODataController
return Ok(layout.FirstOrDefault());
}
- [SwaggerOperation("Get entities from ProductTemplate", OperationId = "GetProductTemplates")]
+ [EndpointDescription("Get entities from ProductTemplate")]
+ [EndpointName("GetProductTemplates")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<LayoutDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Maintenance)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/ShippingMethodController.cs b/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs
similarity index 60%
rename from src/Modules/Grand.Module.Api/Controllers/OData/ShippingMethodController.cs
rename to src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs
index a483c5829..4d233c182 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/ShippingMethodController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Shipping;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Shipping;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/ShippingMethod")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class ShippingMethodController : BaseODataController
+public class ShippingMethodController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class ShippingMethodController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from ShippingMethod by key", OperationId = "GetShippingMethodById")]
+ [EndpointDescription("Get entity from ShippingMethod by key")]
+ [EndpointName("GetShippingMethodById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ShippingMethodDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class ShippingMethodController : BaseODataController
return Ok(shipping.FirstOrDefault());
}
- [SwaggerOperation("Get entities from ShippingMethod", OperationId = "GetShippingMethods")]
+ [EndpointDescription("Get entities from ShippingMethod")]
+ [EndpointName("GetShippingMethods")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<ShippingMethodDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/SpecificationAttributeController.cs b/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs
similarity index 65%
rename from src/Modules/Grand.Module.Api/Controllers/OData/SpecificationAttributeController.cs
rename to src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs
index f33538794..3308cbf48 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/SpecificationAttributeController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs
@@ -1,23 +1,20 @@
-using Grand.Module.Api.Commands.Models.Catalog;
+using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Commands.Models.Catalog;
using Grand.Module.Api.DTOs.Catalog;
using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Permissions;
-using Grand.Domain.Catalog;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/SpecificationAttribute")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class SpecificationAttributeController : BaseODataController
+public class SpecificationAttributeController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -28,27 +25,28 @@ public class SpecificationAttributeController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from SpecificationAttribute by key", OperationId = "GetSpecificationAttributeById")]
+ [EndpointDescription("Get entity from SpecificationAttribute by key")]
+ [EndpointName("GetSpecificationAttributeById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(SpecificationAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();
- var specificationAttribute =
- await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));
+ var specificationAttribute = await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));
if (!specificationAttribute.Any()) return NotFound();
return Ok(specificationAttribute.FirstOrDefault());
}
- [SwaggerOperation("Get entities from SpecificationAttribute", OperationId = "GetSpecificationAttributes")]
+ [EndpointDescription("Get entities from SpecificationAttribute")]
+ [EndpointName("GetSpecificationAttributes")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<SpecificationAttributeDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();
@@ -56,10 +54,11 @@ public class SpecificationAttributeController : BaseODataController
return Ok(await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>()));
}
- [SwaggerOperation("Add new entity to SpecificationAttribute", OperationId = "InsertSpecificationAttribute")]
+ [EndpointDescription("Add new entity to SpecificationAttribute")]
+ [EndpointName("InsertSpecificationAttribute")]
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(SpecificationAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody] SpecificationAttributeDto model)
{
@@ -69,10 +68,11 @@ public class SpecificationAttributeController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Update entity in SpecificationAttribute", OperationId = "UpdateSpecificationAttribute")]
+ [EndpointDescription("Update entity in SpecificationAttribute")]
+ [EndpointName("UpdateSpecificationAttribute")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(SpecificationAttributeDto))]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Put([FromBody] SpecificationAttributeDto model)
{
@@ -82,23 +82,21 @@ public class SpecificationAttributeController : BaseODataController
return Ok(model);
}
- [SwaggerOperation("Partially update entity in SpecificationAttribute",
- OperationId = "PartiallyUpdateSpecificationAttribute")]
+ [EndpointDescription("Partially update entity in SpecificationAttribute")]
+ [EndpointName("PartiallyUpdateSpecificationAttribute")]
[HttpPatch("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Patch([FromRoute] string key,
- [FromBody] JsonPatchDocument<SpecificationAttributeDto> model)
+ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPatchDocument<SpecificationAttributeDto> model)
{
if (string.IsNullOrEmpty(key))
return BadRequest("Key is null or empty");
if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();
- var specification =
- await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));
+ var specification = await _mediator.Send(new GetGenericQuery<SpecificationAttributeDto, SpecificationAttribute>(key));
if (!specification.Any()) return NotFound();
var spec = specification.FirstOrDefault();
@@ -107,12 +105,13 @@ public class SpecificationAttributeController : BaseODataController
return Ok();
}
- [SwaggerOperation("Delete entity in SpecificationAttribute", OperationId = "DeleteSpecificationAttribute")]
- [HttpDelete]
+ [EndpointDescription("Delete entity in SpecificationAttribute")]
+ [EndpointName("DeleteSpecificationAttribute")]
+ [HttpDelete("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
- public async Task<IActionResult> Delete(string key)
+ public async Task<IActionResult> Delete([FromRoute] string key)
{
if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/StoreController.cs b/src/Modules/Grand.Module.Api/Controllers/StoreController.cs
similarity index 60%
rename from src/Modules/Grand.Module.Api/Controllers/OData/StoreController.cs
rename to src/Modules/Grand.Module.Api/Controllers/StoreController.cs
index ffec76512..b4e162880 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/StoreController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/StoreController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Stores;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Common;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Store")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class StoreController : BaseODataController
+public class StoreController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class StoreController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Store by key", OperationId = "GetStoreById")]
+ [EndpointDescription("Get entity from Store by key")]
+ [EndpointName("GetStoreById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(StoreDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class StoreController : BaseODataController
return Ok(store.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Store", OperationId = "GetStores")]
+ [EndpointDescription("Get entities from Store")]
+ [EndpointName("GetStores")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<StoreDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Stores)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenController.cs
index ed7e6c5b3..8dfba281d 100644
--- a/src/Modules/Grand.Module.Api/Controllers/TokenController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/TokenController.cs
@@ -4,7 +4,7 @@ using Grand.Business.Core.Interfaces.Customers;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Http;
namespace Grand.Module.Api.Controllers;
@@ -12,7 +12,6 @@ namespace Grand.Module.Api.Controllers;
[Area("Api")]
[Route("[area]/[controller]/[action]")]
[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-[SwaggerTag("Create token")]
public class TokenController : Controller
{
private readonly IMediator _mediator;
diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
index 795c55d01..58b9b77d0 100644
--- a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
@@ -11,15 +11,15 @@ using MediatR;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Swashbuckle.AspNetCore.Annotations;
using System.Security.Claims;
+using Microsoft.AspNetCore.Http;
namespace Grand.Module.Api.Controllers;
[ApiExplorerSettings(GroupName = "v2")]
[ApiController]
[Route("[controller]/[action]")]
-[SwaggerTag("Create token")]
+[Tags("Create token")]
public class TokenWebController : ControllerBase
{
private readonly IAntiforgery _antiforgery;
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/VendorController.cs b/src/Modules/Grand.Module.Api/Controllers/VendorController.cs
similarity index 60%
rename from src/Modules/Grand.Module.Api/Controllers/OData/VendorController.cs
rename to src/Modules/Grand.Module.Api/Controllers/VendorController.cs
index 5ed176258..97c67fd9a 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/VendorController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/VendorController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Customers;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Vendors;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Customers;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Vendor")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class VendorController : BaseODataController
+public class VendorController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class VendorController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Vendor by key", OperationId = "GetVendorById")]
+ [EndpointDescription("Get entity from Vendor by key")]
+ [EndpointName("GetVendorById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(VendorDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class VendorController : BaseODataController
return Ok(vendor.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Vendor", OperationId = "GetVendors")]
+ [EndpointDescription("Get entities from Vendor")]
+ [EndpointName("GetVendors")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<VendorDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.Vendors)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Controllers/OData/WarehouseController.cs b/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs
similarity index 61%
rename from src/Modules/Grand.Module.Api/Controllers/OData/WarehouseController.cs
rename to src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs
index 4c35bebbb..b02682247 100644
--- a/src/Modules/Grand.Module.Api/Controllers/OData/WarehouseController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs
@@ -1,21 +1,18 @@
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
using Grand.Domain.Shipping;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.DTOs.Shipping;
+using Grand.Module.Api.Queries.Models.Common;
using MediatR;
+using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.OData.Query;
-using MongoDB.AspNetCore.OData;
-using Swashbuckle.AspNetCore.Annotations;
+using Microsoft.AspNetCore.Routing;
using System.Net;
-using Grand.Module.Api.Constants;
-namespace Grand.Module.Api.Controllers.OData;
+namespace Grand.Module.Api.Controllers;
-[Route($"{Configurations.ODataRoutePrefix}/Warehouse")]
-[ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
-public class WarehouseController : BaseODataController
+public class WarehouseController : BaseApiController
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
@@ -26,10 +23,11 @@ public class WarehouseController : BaseODataController
_permissionService = permissionService;
}
- [SwaggerOperation("Get entity from Warehouse by key", OperationId = "GetWarehouseById")]
+ [EndpointDescription("Get entity from Warehouse by key")]
+ [EndpointName("GetWarehouseById")]
[HttpGet("{key}")]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WarehouseDto))]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> Get([FromRoute] string key)
{
@@ -41,11 +39,12 @@ public class WarehouseController : BaseODataController
return Ok(warehouse.FirstOrDefault());
}
- [SwaggerOperation("Get entities from Warehouse", OperationId = "GetWarehouses")]
+ [EndpointDescription("Get entities from Warehouse")]
+ [EndpointName("GetWarehouses")]
[HttpGet]
- [MongoEnableQuery(HandleNullPropagation = HandleNullPropagationOption.False)]
+ [EnableQuery]
[ProducesResponseType((int)HttpStatusCode.Forbidden)]
- [ProducesResponseType((int)HttpStatusCode.OK)]
+ [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IEnumerable<WarehouseDto>))]
public async Task<IActionResult> Get()
{
if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings)) return Forbid();
diff --git a/src/Modules/Grand.Module.Api/Extensions/AddParamOperationFilter.cs b/src/Modules/Grand.Module.Api/Extensions/AddParamOperationFilter.cs
deleted file mode 100644
index 7be72b594..000000000
--- a/src/Modules/Grand.Module.Api/Extensions/AddParamOperationFilter.cs
+++ /dev/null
@@ -1,104 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.OpenApi.Models;
-using Swashbuckle.AspNetCore.SwaggerGen;
-
-namespace Grand.Module.Api.Extensions;
-
-public class AddParamOperationFilter : IOperationFilter
-{
- public void Apply(OpenApiOperation operation, OperationFilterContext context)
- {
- switch (context.ApiDescription.GroupName)
- {
- case "v1" when context.ApiDescription.HttpMethod == "GET" &&
- context.ApiDescription.ParameterDescriptions.Count == 0:
- ApplyV1(operation);
- break;
- case "v2" when context.ApiDescription.HttpMethod == "POST":
- ApplyV2(operation, context);
- break;
- }
- }
-
- private void ApplyV1(OpenApiOperation operation)
- {
- 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"
- }
- });
- operation.Parameters.Add(new OpenApiParameter {
- Name = "$select",
- AllowReserved = true,
- In = ParameterLocation.Query,
- Description = "Select specific properties from the model",
- Required = false,
- Schema = new OpenApiSchema {
- Type = "string"
- }
- });
- }
-
- private void ApplyV2(OpenApiOperation operation, OperationFilterContext context)
- {
- operation.Parameters ??= new List<OpenApiParameter>();
-
- if (context.MethodInfo.GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), true).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 file
diff --git a/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs b/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs
new file mode 100644
index 000000000..6e1266257
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs
@@ -0,0 +1,121 @@
+using Grand.Module.Api.Attributes;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.OpenApi;
+using Microsoft.OpenApi.Models;
+
+namespace Grand.Module.Api.Infrastructure.Extensions
+{
+ public static class OpenApiOptionsExtensions
+ {
+ public static void AddOperationTransformer(this OpenApiOptions options)
+ {
+ options.AddOperationTransformer((operation, context, cancellationToken) =>
+ {
+ var enableQuery = context.Description.ActionDescriptor?.FilterDescriptors.Where(x => x.Filter.GetType() == typeof(EnableQueryAttribute)).FirstOrDefault();
+ if (enableQuery != null)
+ {
+ if (operation.Parameters == null)
+ {
+ operation.Parameters = new List<OpenApiParameter>();
+ }
+
+ 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 = "$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"
+ }
+ });
+ operation.Parameters.Add(new OpenApiParameter {
+ Name = "$select",
+ AllowReserved = true,
+ In = ParameterLocation.Query,
+ Description = "Select specific properties from the model",
+ Required = false,
+ Schema = new OpenApiSchema {
+ Type = "string"
+ }
+ });
+ }
+ return Task.CompletedTask;
+ });
+ }
+ public static void AddCsrfTokenTransformer(this OpenApiOptions options)
+ {
+ options.AddOperationTransformer((operation, context, cancellationToken) =>
+ {
+ operation.Parameters ??= [];
+
+ var antiforgeryToken = context.Description.ActionDescriptor.EndpointMetadata.OfType<AutoValidateAntiforgeryTokenAttribute>().Any();
+ if (antiforgeryToken)
+ operation.Parameters.Add(new OpenApiParameter {
+ Name = "X-CSRF-TOKEN",
+ In = ParameterLocation.Header,
+ Required = true,
+ Schema = new OpenApiSchema {
+ Type = "string",
+ Description = "Antiforgery token"
+ }
+ });
+ return Task.CompletedTask;
+ });
+ }
+ public static void AddContactDocumentTransformer(this OpenApiOptions options, string name, string version)
+ {
+ options.AddDocumentTransformer((document, context, cancellationToken) =>
+ {
+ document.Info = new OpenApiInfo {
+ Description = "Grandnode API",
+ Title = name,
+ Version = version,
+ Contact = new OpenApiContact {
+ Name = name,
+ Email = "[email protected]",
+ Url = new Uri("https://grandnode.com")
+ },
+ License = new OpenApiLicense {
+ Name = "GNU General Public License v3.0",
+ Url = new Uri("https://github.com/grandnode/grandnode2/blob/main/LICENSE")
+ }
+ };
+
+ return Task.CompletedTask;
+ });
+ }
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Extensions/ServiceCollectionExtensions.cs b/src/Modules/Grand.Module.Api/Extensions/ServiceCollectionExtensions.cs
new file mode 100644
index 000000000..c9195e699
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Extensions/ServiceCollectionExtensions.cs
@@ -0,0 +1,78 @@
+using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Directory;
+using Grand.Domain.Localization;
+using Grand.Domain.Media;
+using Grand.Domain.Shipping;
+using Grand.Domain.Stores;
+using Grand.Domain.Vendors;
+using Grand.Module.Api.DTOs.Catalog;
+using Grand.Module.Api.DTOs.Common;
+using Grand.Module.Api.DTOs.Customers;
+using Grand.Module.Api.DTOs.Shipping;
+using Grand.Module.Api.Queries.Handlers.Common;
+using Grand.Module.Api.Queries.Models.Common;
+using MediatR;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Formatters;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+
+namespace Grand.Module.Api.Infrastructure.Extensions
+{
+ public static class ServiceCollectionExtensions
+ {
+ public static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter(this IServiceCollection services)
+ {
+ var builder = new ServiceCollection()
+ .AddLogging()
+ .AddMvc()
+ .AddNewtonsoftJson()
+ .Services.BuildServiceProvider();
+
+ return builder
+ .GetRequiredService<IOptions<MvcOptions>>()
+ .Value
+ .InputFormatters
+ .OfType<NewtonsoftJsonPatchInputFormatter>()
+ .First();
+ }
+ public static void RegisterRequestHandler(this IServiceCollection services)
+ {
+ var handlerTypes = new (Type dto, Type entity)[]
+ {
+ (typeof(CountryDto), typeof(Country)),
+ (typeof(CurrencyDto), typeof(Currency)),
+ (typeof(BrandDto), typeof(Brand)),
+ (typeof(CategoryDto), typeof(Category)),
+ (typeof(CollectionDto), typeof(Collection)),
+ (typeof(ProductAttributeDto), typeof(ProductAttribute)),
+ (typeof(ProductDto), typeof(Product)),
+ (typeof(SpecificationAttributeDto), typeof(SpecificationAttribute)),
+ (typeof(WarehouseDto), typeof(Warehouse)),
+ (typeof(ShippingMethodDto), typeof(ShippingMethod)),
+ (typeof(PickupPointDto), typeof(PickupPoint)),
+ (typeof(DeliveryDateDto), typeof(DeliveryDate)),
+ (typeof(VendorDto), typeof(Vendor)),
+ (typeof(CustomerGroupDto), typeof(CustomerGroup)),
+ (typeof(StoreDto), typeof(Store)),
+ (typeof(LanguageDto), typeof(Language)),
+ (typeof(PictureDto), typeof(Picture)),
+ (typeof(LayoutDto), typeof(BrandLayout)),
+ (typeof(LayoutDto), typeof(CollectionLayout)),
+ (typeof(LayoutDto), typeof(CategoryLayout)),
+ (typeof(LayoutDto), typeof(ProductLayout))
+ };
+
+ foreach (var (dto, entity) in handlerTypes)
+ {
+ var requestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(
+ typeof(GetGenericQuery<,>).MakeGenericType(dto, entity),
+ typeof(IQueryable<>).MakeGenericType(dto)
+ );
+ var handlerImplementationType = typeof(GetGenericQueryHandler<,>).MakeGenericType(dto, entity);
+ services.AddScoped(requestHandlerType, handlerImplementationType);
+ }
+ }
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Extensions/SwaggerODataControllerDocumentFilter.cs b/src/Modules/Grand.Module.Api/Extensions/SwaggerODataControllerDocumentFilter.cs
deleted file mode 100644
index 29a392cde..000000000
--- a/src/Modules/Grand.Module.Api/Extensions/SwaggerODataControllerDocumentFilter.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-using Microsoft.AspNetCore.Mvc.Controllers;
-using Microsoft.OpenApi.Models;
-using Swashbuckle.AspNetCore.SwaggerGen;
-
-namespace Grand.Module.Api.Extensions;
-
-public class SwaggerODataControllerDocumentFilter : IDocumentFilter
-{
- public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
- {
- // remove controller
- foreach (var apiDescription in context.ApiDescriptions)
- {
- var actionDescriptor = (ControllerActionDescriptor)apiDescription.ActionDescriptor;
- if (actionDescriptor.ControllerName == "Metadata")
- swaggerDoc.Paths.Remove($"/{apiDescription.RelativePath}");
- }
-
- // remove schemas
- foreach (var (key, _) in swaggerDoc.Components.Schemas)
- if (key.Contains("Edm") || key.Contains("OData"))
- swaggerDoc.Components.Schemas.Remove(key);
- }
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj b/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj
index 768dca30b..bc103b4bc 100644
--- a/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj
+++ b/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj
@@ -39,18 +39,8 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
- <PackageReference Include="Microsoft.AspNetCore.OData" />
- <PackageReference Include="MongoDB.AspNetCore.OData" >
- <ExcludeAssets>runtime</ExcludeAssets>
- <IncludeAssets>compile</IncludeAssets>
- </PackageReference>
- <PackageReference Include="Swashbuckle.AspNetCore" />
- <PackageReference Include="Swashbuckle.AspNetCore.Annotations" />
+ <PackageReference Include="Microsoft.AspNetCore.OpenApi" />
+ <PackageReference Include="Scalar.AspNetCore" />
+ <PackageReference Include="System.Linq.Dynamic.Core" />
</ItemGroup>
- <Target Name="CopyMongoDBODataDLL" AfterTargets="Build">
- <ItemGroup>
- <MongoDBODataFiles Include="$(NuGetPackageRoot)mongodb.aspnetcore.odata\1.1.0\lib\net5.0\MongoDB.AspNetCore.OData.dll" />
- </ItemGroup>
- <Copy SourceFiles="@(MongoDBODataFiles)" DestinationFolder="$(OutDir)" />
- </Target>
</Project>
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/ApiProviderStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/ApiProviderStartup.cs
deleted file mode 100644
index 87430c0dc..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/ApiProviderStartup.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-using Grand.Module.Api.ApiExplorer;
-using Grand.Infrastructure;
-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.Module.Api.Infrastructure;
-
-/// <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(WebApplication application, IWebHostEnvironment webHostEnvironment)
- {
- }
-
- /// <summary>
- /// Gets order of this startup configuration implementation
- /// </summary>
- public int Priority => 89;
-
- public bool BeforeConfigure => true;
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/DependencyEdmModel.cs b/src/Modules/Grand.Module.Api/Infrastructure/DependencyEdmModel.cs
deleted file mode 100644
index e8302cd02..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/DependencyEdmModel.cs
+++ /dev/null
@@ -1,393 +0,0 @@
-using Grand.Module.Api.DTOs.Catalog;
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.DTOs.Customers;
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Infrastructure.DependencyManagement;
-using Grand.Domain.Catalog;
-using Grand.Infrastructure.Configuration;
-using Microsoft.OData.ModelBuilder;
-
-namespace Grand.Module.Api.Infrastructure;
-
-public class DependencyEdmModel : IDependencyEdmModel
-{
- public void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)
- {
- if (apiConfig.SystemModel)
- {
- RegisterCommon(builder);
- RegisterProduct(builder);
- RegisterCatalog(builder);
- RegisterCustomers(builder);
- RegisterShipping(builder);
- }
- }
-
- public int Order => 0;
-
- protected void RegisterCommon(ODataConventionModelBuilder builder)
- {
- #region Language model
-
- builder.EntitySet<LanguageDto>("Language");
-
- #endregion
-
- #region Currency model
-
- builder.EntitySet<CurrencyDto>("Currency");
-
- #endregion
-
- #region Store model
-
- builder.EntitySet<StoreDto>("Store");
-
- #endregion
-
- #region Country model
-
- builder.EntitySet<CountryDto>("Country");
-
- #endregion
-
- #region layout model
-
- builder.EntitySet<LayoutDto>("CategoryLayout");
- builder.EntitySet<LayoutDto>("CollectionLayout");
- builder.EntitySet<LayoutDto>("ProductLayout");
- builder.EntitySet<LayoutDto>("BrandLayout");
-
- #endregion
-
- #region Picture model
-
- builder.EntitySet<PictureDto>("Picture");
-
- #endregion
- }
-
- protected void RegisterProduct(ODataConventionModelBuilder builder)
- {
- builder.EntitySet<ProductDto>("Product");
- var product = builder.EntityType<ProductDto>();
- builder.ComplexType<ProductCategoryDto>();
- builder.ComplexType<ProductCollectionDto>();
- builder.ComplexType<ProductPictureDto>();
- builder.ComplexType<ProductSpecificationAttributeDto>();
- builder.ComplexType<ProductTierPriceDto>();
- builder.ComplexType<ProductWarehouseInventoryDto>();
- builder.ComplexType<ProductAttributeMappingDto>();
- builder.ComplexType<ProductAttributeValueDto>();
- builder.ComplexType<ProductAttributeCombinationDto>();
- builder.ComplexType<ProductUpdateStock>();
- builder.ComplexType<ProductCategoryDeleteDto>();
- builder.ComplexType<ProductCollectionDeleteDto>();
- builder.ComplexType<ProductPictureDeleteDto>();
- builder.ComplexType<ProductSpecificationAttributeDeleteDto>();
- builder.ComplexType<ProductTierPriceDeleteDto>();
- builder.ComplexType<ProductAttributeMappingDeleteDto>();
-
- //update stock for product
- var updateStock = product.Action("UpdateStock");
- updateStock.Parameter<string>("WarehouseId");
- updateStock.Parameter<int>("Stock").Required();
- updateStock.Returns<bool>();
-
- //insert/update/delete category
-
- #region Product category
-
- var createCategory = product.Action("CreateProductCategory");
- createCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();
- createCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));
- createCategory.Returns<bool>();
-
- var updateCategory = product.Action("UpdateProductCategory");
- updateCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();
- updateCategory.Parameter<bool>(nameof(ProductCategoryDto.IsFeaturedProduct));
- updateCategory.Returns<bool>();
-
- var deleteCategory = product.Action("DeleteProductCategory");
- deleteCategory.Parameter<string>(nameof(ProductCategoryDto.CategoryId)).Required();
- deleteCategory.Returns<bool>();
-
- #endregion
-
- //insert/update/delete collection
-
- #region Product collection
-
- var createCollection = product.Action("CreateProductCollection");
- createCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();
- createCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));
- createCollection.Returns<bool>();
-
- var updateCollection = product.Action("UpdateProductCollection");
- updateCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();
- updateCollection.Parameter<bool>(nameof(ProductCollectionDto.IsFeaturedProduct));
- updateCollection.Returns<bool>();
-
- var deleteCollection = product.Action("DeleteProductCollection");
- deleteCollection.Parameter<string>(nameof(ProductCollectionDto.CollectionId)).Required();
- deleteCollection.Returns<bool>();
-
- #endregion
-
- //insert/update/delete picture
-
- #region Product picture
-
- var createPicture = product.Action("CreateProductPicture");
- createPicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();
- createPicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();
- createPicture.Returns<bool>();
-
- var updatePicture = product.Action("UpdateProductPicture");
- updatePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();
- updatePicture.Parameter<int>(nameof(ProductPictureDto.DisplayOrder)).Required();
- updatePicture.Returns<bool>();
-
- var deletePicture = product.Action("DeleteProductPicture");
- deletePicture.Parameter<string>(nameof(ProductPictureDto.PictureId)).Required();
- deletePicture.Returns<bool>();
-
- #endregion
-
- #region Product specification
-
- var createSpecification = product.Action("CreateProductSpecification");
- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id));
- createSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));
- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));
- //createSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();
- createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));
- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId));
- createSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));
- createSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));
-
- createSpecification.Returns<bool>();
-
- var updateSpecification = product.Action("UpdateProductSpecification");
- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
- updateSpecification.Parameter<int>(nameof(ProductSpecificationAttributeDto.DisplayOrder));
- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.CustomValue));
- //updateSpecification.Parameter<SpecificationAttributeType>(nameof(ProductSpecificationAttributeDto.AttributeType)).Required();
- updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.AllowFiltering));
- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeId))
- .Required();
- updateSpecification.Parameter<bool>(nameof(ProductSpecificationAttributeDto.ShowOnProductPage));
- updateSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.SpecificationAttributeOptionId));
- updateSpecification.Returns<bool>();
-
- var deleteSpecification = product.Action("DeleteProductSpecification");
- deleteSpecification.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
- deleteSpecification.Returns<bool>();
-
- #endregion
-
- #region Product attribute mapping
-
- var createProductAttributeMapping = product.Action("CreateProductAttributeMapping");
- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id));
- createProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));
- createProductAttributeMapping
- .Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();
- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));
- createProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));
- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));
- createProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto
- .ValidationFileAllowedExtensions));
- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));
- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));
- createProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));
- createProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(
- nameof(ProductAttributeMappingDto.ProductAttributeValues));
- createProductAttributeMapping.Returns<ProductAttributeMappingDto>();
-
- var updateProductAttributeMapping = product.Action("UpdateProductAttributeMapping");
- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.Id)).Required();
- updateProductAttributeMapping.Parameter<int>(nameof(ProductAttributeMappingDto.DisplayOrder));
- updateProductAttributeMapping
- .Parameter<AttributeControlType>(nameof(ProductAttributeMappingDto.AttributeControlTypeId)).Required();
- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.DefaultValue));
- updateProductAttributeMapping.Parameter<bool>(nameof(ProductAttributeMappingDto.IsRequired));
- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto.TextPrompt));
- updateProductAttributeMapping.Parameter<string>(nameof(ProductAttributeMappingDto
- .ValidationFileAllowedExtensions));
- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationFileMaximumSize));
- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMaxLength));
- updateProductAttributeMapping.Parameter<int?>(nameof(ProductAttributeMappingDto.ValidationMinLength));
- updateProductAttributeMapping.Parameter<List<ProductAttributeValueDto>>(
- nameof(ProductAttributeMappingDto.ProductAttributeValues));
- updateProductAttributeMapping.Returns<ProductAttributeMappingDto>();
-
- var deleteProductAttributeMapping = product.Action("DeleteProductAttributeMapping");
- deleteProductAttributeMapping.Parameter<string>(nameof(ProductSpecificationAttributeDto.Id)).Required();
- deleteProductAttributeMapping.Returns<bool>();
-
- #endregion
-
- //insert/update/delete tier price
-
- #region Product tierprice
-
- var createTierPrice = product.Action("CreateProductTierPrice");
- createTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));
- createTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));
- createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));
- createTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));
- createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));
- createTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));
- createTierPrice.Returns<bool>();
-
- var updateTierPrice = product.Action("UpdateProductTierPrice");
- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();
- updateTierPrice.Parameter<int>(nameof(ProductTierPriceDto.Quantity));
- updateTierPrice.Parameter<double>(nameof(ProductTierPriceDto.Price));
- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.StoreId));
- updateTierPrice.Parameter<string>(nameof(ProductTierPriceDto.CustomerGroupId));
- updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.StartDateTimeUtc));
- updateTierPrice.Parameter<DateTime?>(nameof(ProductTierPriceDto.EndDateTimeUtc));
- updateTierPrice.Returns<bool>();
-
- var deleteTierPrice = product.Action("DeleteProductTierPrice");
- deleteTierPrice.Parameter<string>(nameof(ProductTierPriceDto.Id)).Required();
- deleteTierPrice.Returns<bool>();
-
- #endregion
- }
-
- protected void RegisterCatalog(ODataConventionModelBuilder builder)
- {
- #region Category model
-
- builder.EntitySet<CategoryDto>("Category");
-
- #endregion
-
- #region Brand model
-
- builder.EntitySet<BrandDto>("Brand");
-
- #endregion
-
- #region Collection model
-
- builder.EntitySet<CollectionDto>("Collection");
-
- #endregion
-
- #region Product attribute model
-
- builder.EntitySet<ProductAttributeDto>("ProductAttribute");
- builder.ComplexType<PredefinedProductAttributeValueDto>();
-
- #endregion
-
- #region Product attribute model
-
- builder.EntitySet<SpecificationAttributeDto>("SpecificationAttribute");
- builder.ComplexType<SpecificationAttributeOptionDto>();
-
- #endregion
- }
-
- protected void RegisterCustomers(ODataConventionModelBuilder builder)
- {
- #region Customer
-
- builder.EntitySet<CustomerDto>("Customer");
- var customer = builder.EntityType<CustomerDto>();
- builder.ComplexType<AddressDto>();
- builder.ComplexType<DeleteAddressDto>();
- builder.ComplexType<PasswordDto>();
-
- var addAddress = customer.Action("AddAddress");
- addAddress.Parameter<string>(nameof(AddressDto.Id)).Required();
- addAddress.Parameter<string>(nameof(AddressDto.City));
- addAddress.Parameter<string>(nameof(AddressDto.Email));
- addAddress.Parameter<string>(nameof(AddressDto.Company));
- addAddress.Parameter<string>(nameof(AddressDto.Address1));
- addAddress.Parameter<string>(nameof(AddressDto.Address2));
- addAddress.Parameter<string>(nameof(AddressDto.LastName));
- addAddress.Parameter<string>(nameof(AddressDto.CountryId));
- addAddress.Parameter<string>(nameof(AddressDto.FaxNumber));
- addAddress.Parameter<string>(nameof(AddressDto.FirstName));
- addAddress.Parameter<string>(nameof(AddressDto.VatNumber));
- addAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));
- addAddress.Parameter<string>(nameof(AddressDto.Note));
- addAddress.Parameter<int>(nameof(AddressDto.AddressType));
- addAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));
- addAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));
- addAddress.Returns<AddressDto>();
-
- var updateAddress = customer.Action("UpdateAddress");
- updateAddress.Parameter<string>(nameof(AddressDto.Id)).Required();
- updateAddress.Parameter<string>(nameof(AddressDto.City));
- updateAddress.Parameter<string>(nameof(AddressDto.Email));
- updateAddress.Parameter<string>(nameof(AddressDto.Company));
- updateAddress.Parameter<string>(nameof(AddressDto.Address1));
- updateAddress.Parameter<string>(nameof(AddressDto.Address2));
- updateAddress.Parameter<string>(nameof(AddressDto.LastName));
- updateAddress.Parameter<string>(nameof(AddressDto.CountryId));
- updateAddress.Parameter<string>(nameof(AddressDto.FaxNumber));
- updateAddress.Parameter<string>(nameof(AddressDto.FirstName));
- updateAddress.Parameter<string>(nameof(AddressDto.VatNumber));
- updateAddress.Parameter<string>(nameof(AddressDto.PhoneNumber));
- updateAddress.Parameter<string>(nameof(AddressDto.Note));
- updateAddress.Parameter<int>(nameof(AddressDto.AddressType));
- updateAddress.Parameter<string>(nameof(AddressDto.ZipPostalCode));
- updateAddress.Parameter<string>(nameof(AddressDto.StateProvinceId));
- updateAddress.Returns<AddressDto>();
-
- var deleteAddress = customer.Action("DeleteAddress");
- deleteAddress.Parameter<string>(nameof(DeleteAddressDto.AddressId));
- deleteAddress.Returns<bool>();
-
- var changePassword = customer.Action("SetPassword");
- changePassword.Parameter<string>(nameof(PasswordDto.Password));
- changePassword.Returns<bool>();
-
- #endregion
-
- #region Customer group model
-
- builder.EntitySet<CustomerGroupDto>("CustomerGroup");
-
- #endregion
-
- #region Vendors
-
- builder.EntitySet<VendorDto>("Vendor");
-
- #endregion
- }
-
- protected void RegisterShipping(ODataConventionModelBuilder builder)
- {
- #region Warehouse model
-
- builder.EntitySet<WarehouseDto>("Warehouse");
-
- #endregion
-
- #region Delivery date model
-
- builder.EntitySet<DeliveryDateDto>("DeliveryDate");
-
- #endregion
-
- #region Pickup point model
-
- builder.EntitySet<PickupPointDto>("PickupPoint");
-
- #endregion
-
- #region Shipping method model
-
- builder.EntitySet<ShippingMethodDto>("ShippingMethod");
-
- #endregion
- }
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs b/src/Modules/Grand.Module.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs
deleted file mode 100644
index fde25a8db..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/DependencyManagement/IDependencyEdmModel.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-using Grand.Infrastructure.Configuration;
-using Microsoft.OData.ModelBuilder;
-
-namespace Grand.Module.Api.Infrastructure.DependencyManagement;
-
-public interface IDependencyEdmModel
-{
- /// <summary>
- /// Order of this dependency implementation
- /// </summary>
- int Order { get; }
-
- /// <summary>
- /// Register edmmodel
- /// </summary>
- /// <param name="builder">OData Convention Model Builder</param>
- /// <param name="apiConfig">ApiConfig</param>
- void Register(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig);
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/Filters/EnumSchemaFilter.cs b/src/Modules/Grand.Module.Api/Infrastructure/Filters/EnumSchemaFilter.cs
deleted file mode 100644
index 0b7190031..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/Filters/EnumSchemaFilter.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using Microsoft.OpenApi.Any;
-using Microsoft.OpenApi.Models;
-using Swashbuckle.AspNetCore.SwaggerGen;
-
-namespace Grand.Module.Api.Infrastructure.Filters;
-
-public class EnumSchemaFilter : ISchemaFilter
-{
- public void Apply(OpenApiSchema schema, SchemaFilterContext context)
- {
- if (!context.Type.IsEnum) return;
-
- var enumValues = schema.Enum.ToArray();
- foreach (var item in enumValues)
- {
- var value = (OpenApiPrimitive<int>)item;
- var name = Enum.GetName(context.Type, value.Value);
- schema.Description += $"{value.Value} - {name}; ";
- }
- }
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/ODataStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/ODataStartup.cs
deleted file mode 100644
index 88f63a31e..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/ODataStartup.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-using Grand.Module.Api.Constants;
-using Grand.Module.Api.DTOs.Catalog;
-using Grand.Module.Api.DTOs.Common;
-using Grand.Module.Api.DTOs.Customers;
-using Grand.Module.Api.DTOs.Shipping;
-using Grand.Module.Api.Infrastructure.DependencyManagement;
-using Grand.Module.Api.Queries.Handlers.Common;
-using Grand.Module.Api.Queries.Models.Common;
-using Grand.Domain.Catalog;
-using Grand.Domain.Customers;
-using Grand.Domain.Directory;
-using Grand.Domain.Localization;
-using Grand.Domain.Media;
-using Grand.Domain.Shipping;
-using Grand.Domain.Stores;
-using Grand.Domain.Vendors;
-using Grand.Infrastructure;
-using Grand.Infrastructure.Configuration;
-using Grand.Infrastructure.TypeSearch;
-using MediatR;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.Mvc.Formatters;
-using Microsoft.AspNetCore.OData;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Options;
-using Microsoft.OData.Edm;
-using Microsoft.OData.ModelBuilder;
-
-namespace Grand.Module.Api.Infrastructure;
-
-public class ODataStartup : IStartupApplication
-{
- public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
- {
- }
-
- public void ConfigureServices(IServiceCollection services,
- IConfiguration configuration)
- {
- var apiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();
- if (apiConfig.Enabled)
- {
- //register RequestHandler
- RegisterRequestHandler(services);
-
- //Add OData
- services.AddControllers(options =>
- {
- options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
- }).AddOData(opt =>
- {
- opt.EnableQueryFeatures(Configurations.MaxLimit);
- opt.AddRouteComponents(Configurations.ODataRoutePrefix, GetEdmModel(apiConfig));
- opt.Select().Filter().OrderBy().Expand().Count().SetMaxTop(Configurations.MaxLimit);
- });
-
- services.AddScoped<ModelValidationAttribute>();
- }
- }
-
- public int Priority => 505;
- public bool BeforeConfigure => false;
-
- private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
- {
- var builder = new ServiceCollection()
- .AddLogging()
- .AddMvc()
- .AddNewtonsoftJson()
- .Services.BuildServiceProvider();
-
- return builder
- .GetRequiredService<IOptions<MvcOptions>>()
- .Value
- .InputFormatters
- .OfType<NewtonsoftJsonPatchInputFormatter>()
- .First();
- }
-
-
- private IEdmModel GetEdmModel(BackendAPIConfig apiConfig)
- {
- var builder = new ODataConventionModelBuilder {
- Namespace = Configurations.ODataModelBuilderNamespace
- };
- RegisterDependencies(builder, apiConfig);
- return builder.GetEdmModel();
- }
-
- private void RegisterDependencies(ODataConventionModelBuilder builder, BackendAPIConfig apiConfig)
- {
- var typeFinder = new TypeSearcher();
-
- //find dependency provided by other assemblies
- var dependencyInject = typeFinder.ClassesOfType<IDependencyEdmModel>();
-
- //create and sort instances of dependency inject
- var instances = dependencyInject
- .Select(di => (IDependencyEdmModel)Activator.CreateInstance(di))
- .OrderBy(di => di!.Order);
-
- //register all provided dependencies
- foreach (var dependencyRegistrar in instances)
- dependencyRegistrar!.Register(builder, apiConfig);
- }
-
- private void RegisterRequestHandler(IServiceCollection services)
- {
- var handlerTypes = new (Type dto, Type entity)[]
- {
- (typeof(CountryDto), typeof(Country)),
- (typeof(CurrencyDto), typeof(Currency)),
- (typeof(BrandDto), typeof(Brand)),
- (typeof(CategoryDto), typeof(Category)),
- (typeof(CollectionDto), typeof(Collection)),
- (typeof(ProductAttributeDto), typeof(ProductAttribute)),
- (typeof(ProductDto), typeof(Product)),
- (typeof(SpecificationAttributeDto), typeof(SpecificationAttribute)),
- (typeof(WarehouseDto), typeof(Warehouse)),
- (typeof(ShippingMethodDto), typeof(ShippingMethod)),
- (typeof(PickupPointDto), typeof(PickupPoint)),
- (typeof(DeliveryDateDto), typeof(DeliveryDate)),
- (typeof(VendorDto), typeof(Vendor)),
- (typeof(CustomerGroupDto), typeof(CustomerGroup)),
- (typeof(StoreDto), typeof(Store)),
- (typeof(LanguageDto), typeof(Language)),
- (typeof(PictureDto), typeof(Picture)),
- (typeof(LayoutDto), typeof(BrandLayout)),
- (typeof(LayoutDto), typeof(CollectionLayout)),
- (typeof(LayoutDto), typeof(CategoryLayout)),
- (typeof(LayoutDto), typeof(ProductLayout))
- };
-
- foreach (var (dto, entity) in handlerTypes)
- {
- var requestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(
- typeof(GetGenericQuery<,>).MakeGenericType(dto, entity),
- typeof(IQueryable<>).MakeGenericType(dto)
- );
- var handlerImplementationType = typeof(GetGenericQueryHandler<,>).MakeGenericType(dto, entity);
- services.AddScoped(requestHandlerType, handlerImplementationType);
- }
- }
-
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs
new file mode 100644
index 000000000..e0637ad46
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs
@@ -0,0 +1,95 @@
+using Grand.Infrastructure;
+using Grand.Infrastructure.Configuration;
+using Grand.Module.Api.ApiExplorer;
+using Grand.Module.Api.Attributes;
+using Grand.Module.Api.Infrastructure.Extensions;
+using Grand.Module.Api.Infrastructure.Transformers;
+using Grand.SharedKernel.Extensions;
+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;
+using Microsoft.Extensions.Hosting;
+using Scalar.AspNetCore;
+
+namespace Grand.Module.Api.Infrastructure;
+
+public class OpenApiStartup : IStartupApplication
+{
+ public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
+ {
+ application.MapOpenApi();
+ if (application.Environment.IsDevelopment())
+ {
+ application.MapScalarApiReference(options =>
+ {
+ options.WithTitle("OpenApi Playground");
+ options.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
+ });
+ }
+ }
+
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
+ {
+ var backendApiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();
+ var frontApiConfig = services.BuildServiceProvider().GetService<FrontendAPIConfig>();
+ var webHostEnvironment = services.BuildServiceProvider().GetService<IWebHostEnvironment>();
+
+ if (webHostEnvironment.IsDevelopment() && (backendApiConfig.Enabled || frontApiConfig.Enabled))
+ {
+ if (backendApiConfig.Enabled)
+ {
+ ConfigureBackendApi(services);
+ }
+ if (frontApiConfig.Enabled)
+ {
+ ConfigureFrontendApi(services);
+ }
+ }
+
+ if (backendApiConfig.Enabled)
+ {
+ //register RequestHandler
+ services.RegisterRequestHandler();
+
+ //Add JsonPatchInputFormatter
+ services.AddControllers(options =>
+ {
+ options.InputFormatters.Insert(0, services.GetJsonPatchInputFormatter());
+ });
+ services.AddScoped<ModelValidationAttribute>();
+ }
+ }
+ public int Priority => 505;
+ public bool BeforeConfigure => false;
+
+ private void ConfigureBackendApi(IServiceCollection services)
+ {
+ services.AddOpenApi(ApiConstants.ApiGroupNameV1, options =>
+ {
+ options.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0;
+ options.AddContactDocumentTransformer("Grandnode Backend API", ApiConstants.ApiGroupNameV1);
+ options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
+ options.AddSchemaTransformer<EnumSchemaTransformer>();
+ options.AddOperationTransformer();
+ });
+ }
+
+ private void ConfigureFrontendApi(IServiceCollection services)
+ {
+ services.AddOpenApi(ApiConstants.ApiGroupNameV2, options =>
+ {
+ options.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0;
+ options.AddContactDocumentTransformer("Grandnode Frontend API", ApiConstants.ApiGroupNameV2);
+ options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
+ options.AddSchemaTransformer<EnumSchemaTransformer>();
+ options.AddSchemaTransformer<IgnoreFieldSchemaTransformer>();
+ options.AddCsrfTokenTransformer();
+ });
+
+ //api description provider
+ services.TryAddEnumerable(ServiceDescriptor.Transient<IApiDescriptionProvider, MetadataApiDescriptionProvider>());
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/SwaggerStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/SwaggerStartup.cs
deleted file mode 100644
index 57dc59aa0..000000000
--- a/src/Modules/Grand.Module.Api/Infrastructure/SwaggerStartup.cs
+++ /dev/null
@@ -1,113 +0,0 @@
-using Grand.Module.Api.Extensions;
-using Grand.Module.Api.Infrastructure.Filters;
-using Grand.Infrastructure;
-using Grand.Infrastructure.Configuration;
-using Microsoft.AspNetCore.Authentication.JwtBearer;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.OData;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using Microsoft.OpenApi.Models;
-
-namespace Grand.Module.Api.Infrastructure;
-
-public class SwaggerStartup : IStartupApplication
-{
- public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)
- {
- var backendApiConfig = application.Services.GetService<BackendAPIConfig>();
- var frontApiConfig = application.Services.GetService<FrontendAPIConfig>();
- if (backendApiConfig.Enabled)
- application.UseODataQueryRequest();
-
- if (webHostEnvironment.IsDevelopment() && (backendApiConfig.Enabled || frontApiConfig.Enabled))
- {
- application.UseSwagger();
- application.UseSwaggerUI(c =>
- {
- if (backendApiConfig.Enabled)
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "Grandnode Backend API");
-
- if (frontApiConfig.Enabled)
- c.SwaggerEndpoint("/swagger/v2/swagger.json", "Grandnode Frontend API");
- });
- }
- }
-
- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
- {
- var backendApiConfig = services.BuildServiceProvider().GetService<BackendAPIConfig>();
- var frontApiConfig = services.BuildServiceProvider().GetService<FrontendAPIConfig>();
- var webHostEnvironment = services.BuildServiceProvider().GetService<IWebHostEnvironment>();
-
- if (webHostEnvironment.IsDevelopment() && (backendApiConfig.Enabled || frontApiConfig.Enabled))
- services.AddSwaggerGen(c =>
- {
- if (backendApiConfig.Enabled)
- c.SwaggerDoc("v1", new OpenApiInfo {
- Title = "Grandnode Backend API",
- Version = "v1",
- Contact = GetOpenApiContact(),
- License = GetOpenApiLicense()
- });
-
- if (frontApiConfig.Enabled)
- c.SwaggerDoc("v2", new OpenApiInfo {
- Title = "Grandnode Frontend API",
- Version = "v2",
- Contact = GetOpenApiContact(),
- License = GetOpenApiLicense()
- });
-
- c.CustomSchemaIds(s => s.FullName?.Replace("+", "."));
- c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, //Name the security scheme
- new OpenApiSecurityScheme {
- Description = "JWT Authorization header using the Bearer scheme.",
- Type = SecuritySchemeType
- .Http, //We set the scheme type to http since we're using bearer authentication
- Scheme =
- "bearer" //The name of the HTTP Authorization scheme to be used in the Authorization header. In this case "bearer".
- });
-
- c.AddSecurityRequirement(new OpenApiSecurityRequirement {
- {
- new OpenApiSecurityScheme {
- Reference = new OpenApiReference {
- Id = JwtBearerDefaults.AuthenticationScheme,
- Type //The name of the previously defined security scheme.
- = ReferenceType.SecurityScheme
- }
- },
- new List<string>()
- }
- });
- c.OperationFilter<AddParamOperationFilter>();
- c.DocumentFilter<SwaggerODataControllerDocumentFilter>();
- c.EnableAnnotations();
- c.SchemaFilter<EnumSchemaFilter>();
- c.SchemaFilter<IgnoreFieldFilter>();
- });
- }
-
- public int Priority => 90;
- public bool BeforeConfigure => true;
-
- private OpenApiContact GetOpenApiContact()
- {
- return new OpenApiContact {
- Name = "Grandnode",
- Email = "[email protected]",
- Url = new Uri("https://grandnode.com")
- };
- }
-
- private OpenApiLicense GetOpenApiLicense()
- {
- return new OpenApiLicense {
- Name = "GNU General Public License v3.0",
- Url = new Uri("https://github.com/grandnode/grandnode2/blob/main/LICENSE")
- };
- }
-}
\ No newline at end of file
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/Transformers/BearerSecuritySchemeTransformer.cs b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/BearerSecuritySchemeTransformer.cs
new file mode 100644
index 000000000..9498d77cd
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/BearerSecuritySchemeTransformer.cs
@@ -0,0 +1,25 @@
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.OpenApi;
+using Microsoft.OpenApi.Models;
+
+namespace Grand.Module.Api.Infrastructure.Transformers;
+internal sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
+{
+ public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
+ {
+ var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
+ if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
+ {
+ var requirements = new Dictionary<string, OpenApiSecurityScheme> {
+ ["Bearer"] = new OpenApiSecurityScheme {
+ Type = SecuritySchemeType.Http,
+ Scheme = "bearer",
+ In = ParameterLocation.Header,
+ BearerFormat = "Json Web Token"
+ }
+ };
+ document.Components ??= new OpenApiComponents();
+ document.Components.SecuritySchemes = requirements;
+ }
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/Transformers/EnumSchemaTransformer.cs b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/EnumSchemaTransformer.cs
new file mode 100644
index 000000000..9761f89bf
--- /dev/null
+++ b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/EnumSchemaTransformer.cs
@@ -0,0 +1,21 @@
+using Microsoft.AspNetCore.OpenApi;
+using Microsoft.OpenApi.Models;
+
+namespace Grand.Module.Api.Infrastructure.Transformers;
+
+public class EnumSchemaTransformer : IOpenApiSchemaTransformer
+{
+ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
+ {
+ if (context.JsonTypeInfo.Type.IsEnum)
+ {
+ var enumValues = Enum.GetValues(context.JsonTypeInfo.Type);
+ foreach (var item in enumValues)
+ {
+ var name = Enum.GetName(context.JsonTypeInfo.Type, item);
+ schema.Description += $"{(int)item} - {name}; ";
+ }
+ }
+ return Task.CompletedTask;
+ }
+}
diff --git a/src/Modules/Grand.Module.Api/Infrastructure/Filters/IgnoreFieldFilter.cs b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/IgnoreFieldSchemaTransformer.cs
similarity index 55%
rename from src/Modules/Grand.Module.Api/Infrastructure/Filters/IgnoreFieldFilter.cs
rename to src/Modules/Grand.Module.Api/Infrastructure/Transformers/IgnoreFieldSchemaTransformer.cs
index 90995b07d..c0380cb02 100644
--- a/src/Modules/Grand.Module.Api/Infrastructure/Filters/IgnoreFieldFilter.cs
+++ b/src/Modules/Grand.Module.Api/Infrastructure/Transformers/IgnoreFieldSchemaTransformer.cs
@@ -1,16 +1,17 @@
using Grand.SharedKernel.Attributes;
+using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;
-using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
-namespace Grand.Module.Api.Infrastructure.Filters;
+namespace Grand.Module.Api.Infrastructure.Transformers;
-public class IgnoreFieldFilter : ISchemaFilter
+public class IgnoreFieldSchemaTransformer : IOpenApiSchemaTransformer
{
- public void Apply(OpenApiSchema schema, SchemaFilterContext context)
+ public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
{
- var type = context.Type;
- if (!schema.Properties.Any() || type == null) return;
+
+ var type = context.JsonTypeInfo.Type;
+ if (!schema.Properties.Any() || type == null) return Task.CompletedTask;
var excludedPropertyNames = type
.GetProperties()
@@ -18,7 +19,7 @@ public class IgnoreFieldFilter : ISchemaFilter
t => t.GetCustomAttribute<IgnoreApiAttribute>() != null
).Select(d => d.Name).ToList();
- if (!excludedPropertyNames.Any()) return;
+ if (!excludedPropertyNames.Any()) return Task.CompletedTask;
var excludedSchemaPropertyKey = schema.Properties
.Where(
@@ -28,5 +29,8 @@ public class IgnoreFieldFilter : ISchemaFilter
).Select(ap => ap.Key);
foreach (var propertyToExclude in excludedSchemaPropertyKey) schema.Properties.Remove(propertyToExclude);
+
+ return Task.CompletedTask;
+ //throw new NotImplementedException();
}
-}
\ No newline at end of file
+}
diff --git a/src/Modules/Grand.Module.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs b/src/Modules/Grand.Module.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs
index 5a4d10a95..befbdebfc 100644
--- a/src/Modules/Grand.Module.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs
+++ b/src/Modules/Grand.Module.Api/Queries/Handlers/Common/GetGenericQueryHandler.cs
@@ -20,6 +20,7 @@ public class GetGenericQueryHandler<T, C> : IRequestHandler<GetGenericQuery<T, C
public async Task<IQueryable<T>> Handle(GetGenericQuery<T, C> request, CancellationToken cancellationToken)
{
var query = _repository.TableCollection<T>();
+
if (string.IsNullOrEmpty(request.Id))
return query;
return await Task.FromResult(query.Where(x => x.Id == request.Id));
diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs
index df79fb8ce..db80d9d4a 100644
--- a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs
+++ b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs
@@ -4,5 +4,4 @@ using MediatR;
namespace Grand.Module.Api.Queries.Models.Common;
-public record GetGenericQuery<T, C>(string Id = null)
- : IRequest<IQueryable<T>> where T : BaseApiEntityModel where C : BaseEntity;
\ No newline at end of file
+public record GetGenericQuery<T, C>(string Id = null) : IRequest<IQueryable<T>> where T : BaseApiEntityModel where C : BaseEntity;
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
index dcf461186..1b82e3231 100644
--- a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
@@ -15,7 +15,7 @@ public class CultureSettingMiddleware
public async Task InvokeAsync(HttpContext context, IWorkContextAccessor workContextAccessor)
{
- if (workContextAccessor.WorkContext.WorkingLanguage != null)
+ if (workContextAccessor.WorkContext?.WorkingLanguage != null)
{
var culture = new CultureInfo(workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture);
diff --git a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
index 2ea239085..ea200818b 100644
--- a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
@@ -1,5 +1,6 @@
using Grand.Infrastructure;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
namespace Grand.Web.Common.Middleware;
@@ -9,6 +10,8 @@ public class WorkContextMiddleware
private readonly RequestDelegate _next;
+ private readonly List<string> skipRoutePattern = ["/scalar/{documentName}", "/openapi/{documentName}.json"];
+
#endregion
#region Ctor
@@ -35,6 +38,17 @@ public class WorkContextMiddleware
public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContextSetter, IWorkContextAccessor workContextAccessor)
{
if (context?.Request == null) return;
+
+ var endpoint = context.GetEndpoint();
+ if (endpoint != null)
+ {
+ var routePattern = (endpoint as RouteEndpoint)?.RoutePattern.RawText;
+ if (routePattern != null && skipRoutePattern.Any(pattern => routePattern.StartsWith(pattern, StringComparison.OrdinalIgnoreCase)))
+ {
+ await _next(context);
+ return;
+ }
+ }
//set current context
var workContext = await workContextSetter.InitializeWorkContext();
diff --git a/src/Web/Grand.Web.Common/WorkContextSetter.cs b/src/Web/Grand.Web.Common/WorkContextSetter.cs
index 97256e0a1..aeafa29aa 100644
--- a/src/Web/Grand.Web.Common/WorkContextSetter.cs
+++ b/src/Web/Grand.Web.Common/WorkContextSetter.cs
@@ -175,21 +175,21 @@ public class WorkContextSetter : IWorkContextSetter
var customer = await GetBackgroundTaskCustomer();
if (customer != null) return customer;
- customer = await GetAuthenticatedCustomer();
+ customer = await GetAllowAnonymousCustomer();
if (customer != null) return customer;
- customer = await GetGuestCustomer();
+ customer = await GetCookieAuthenticatedCustomer();
if (customer != null) return customer;
- customer = await GetApiUserCustomer();
+ customer = await GetGuestCustomer();
if (customer != null) return customer;
customer = await GetSearchEngineCustomer();
if (customer != null) return customer;
- customer = await GetAllowAnonymousCustomer();
+ customer = await GetApiUserCustomer();
if (customer != null) return customer;
-
+
//create guest if not exists
customer = await CreateCustomerGuest(store);
@@ -211,7 +211,7 @@ public class WorkContextSetter : IWorkContextSetter
return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);
}
- private async Task<Customer> GetAuthenticatedCustomer()
+ private async Task<Customer> GetCookieAuthenticatedCustomer()
{
var customer = await _authenticationService.GetAuthenticatedCustomer();
if (customer == null) return null;
@@ -227,8 +227,7 @@ public class WorkContextSetter : IWorkContextSetter
private async Task<Customer> GetApiUserCustomer()
{
- var apiAuthenticationService =
- _httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();
+ var apiAuthenticationService = _httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();
return await apiAuthenticationService.GetAuthenticatedCustomer();
}
diff --git a/src/Web/Grand.Web/Controllers/BlogController.cs b/src/Web/Grand.Web/Controllers/BlogController.cs
index 3561642c4..4de063c03 100644
--- a/src/Web/Grand.Web/Controllers/BlogController.cs
+++ b/src/Web/Grand.Web/Controllers/BlogController.cs
@@ -16,9 +16,11 @@ using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
+using Grand.SharedKernel.Attributes;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class BlogController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/CatalogController.cs b/src/Web/Grand.Web/Controllers/CatalogController.cs
index 956ca76bf..736e6a689 100644
--- a/src/Web/Grand.Web/Controllers/CatalogController.cs
+++ b/src/Web/Grand.Web/Controllers/CatalogController.cs
@@ -9,7 +9,6 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Permissions;
using Grand.Domain.Catalog;
-using Grand.Domain.Customers;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
using Grand.Web.Commands.Models.Vendors;
@@ -21,9 +20,12 @@ using Grand.Web.Models.Catalog;
using Grand.Web.Models.Vendors;
using MediatR;
using Microsoft.AspNetCore.Mvc;
+using Grand.SharedKernel.Attributes;
+using Microsoft.AspNetCore.Http;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CatalogController : BasePublicController
{
#region Constructors
@@ -89,6 +91,7 @@ public class CatalogController : BasePublicController
#region Categories
+ [ProducesResponseType(typeof(CategoryModel), StatusCodes.Status200OK)]
[HttpGet]
public virtual async Task<IActionResult> Category(string categoryId, CatalogPagingFilteringModel command)
{
@@ -319,8 +322,7 @@ public class CatalogController : BasePublicController
[HttpPost]
[AutoValidateAntiforgeryToken]
[DenySystemAccount]
- public virtual async Task<IActionResult> VendorReviews(
- VendorReviewsModel model)
+ public virtual async Task<IActionResult> VendorReviews(VendorReviewsModel model)
{
var vendor = await _vendorService.GetVendorById(model.VendorId);
if (vendor is not { Active: true } || !vendor.AllowCustomerReviews)
diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs
index 8e885a7a6..4b9deb1f2 100644
--- a/src/Web/Grand.Web/Controllers/CheckoutController.cs
+++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs
@@ -16,6 +16,7 @@ using Grand.Domain.Payments;
using Grand.Domain.Shipping;
using Grand.Infrastructure;
using Grand.Infrastructure.Extensions;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Extensions;
@@ -30,6 +31,7 @@ using Microsoft.Extensions.Logging;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CheckoutController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.cs
index 408fda09b..9e9c71e6f 100644
--- a/src/Web/Grand.Web/Controllers/CommonController.cs
+++ b/src/Web/Grand.Web/Controllers/CommonController.cs
@@ -29,6 +29,7 @@ using System.Net;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CommonController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.cs
index 38cc5ecc6..b82df5ee5 100644
--- a/src/Web/Grand.Web/Controllers/ContactController.cs
+++ b/src/Web/Grand.Web/Controllers/ContactController.cs
@@ -6,6 +6,7 @@ using Grand.Domain.Catalog;
using Grand.Domain.Media;
using Grand.Domain.Stores;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Commands.Models.Contact;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Extensions;
@@ -18,6 +19,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class ContactController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/CountryController.cs b/src/Web/Grand.Web/Controllers/CountryController.cs
index c927bb37b..36129eaa1 100644
--- a/src/Web/Grand.Web/Controllers/CountryController.cs
+++ b/src/Web/Grand.Web/Controllers/CountryController.cs
@@ -1,4 +1,5 @@
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Features.Models.Common;
@@ -8,6 +9,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CountryController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/CourseController.cs b/src/Web/Grand.Web/Controllers/CourseController.cs
index 8345b6060..067f22cc1 100644
--- a/src/Web/Grand.Web/Controllers/CourseController.cs
+++ b/src/Web/Grand.Web/Controllers/CourseController.cs
@@ -12,9 +12,11 @@ using Grand.Web.Common.Controllers;
using Grand.Web.Features.Models.Courses;
using MediatR;
using Microsoft.AspNetCore.Mvc;
+using Grand.SharedKernel.Attributes;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class CourseController : BasePublicController
{
private readonly IAclService _aclService;
diff --git a/src/Web/Grand.Web/Controllers/DownloadController.cs b/src/Web/Grand.Web/Controllers/DownloadController.cs
index 3f27f7911..c17178b0a 100644
--- a/src/Web/Grand.Web/Controllers/DownloadController.cs
+++ b/src/Web/Grand.Web/Controllers/DownloadController.cs
@@ -9,6 +9,7 @@ using Grand.Domain.Catalog;
using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Microsoft.AspNetCore.Mvc;
@@ -19,6 +20,7 @@ using OperatingSystem = Grand.Infrastructure.OperatingSystem;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class DownloadController : BasePublicController
{
private readonly CustomerSettings _customerSettings;
diff --git a/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs b/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
index 2623d09b9..ff77326fa 100644
--- a/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
+++ b/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
@@ -18,9 +18,11 @@ using Grand.Web.Events.Cache;
using Grand.Web.Extensions;
using Grand.Web.Models.Knowledgebase;
using Microsoft.AspNetCore.Mvc;
+using Grand.SharedKernel.Attributes;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class KnowledgebaseController : BasePublicController
{
private readonly IAclService _aclService;
diff --git a/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs b/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
index 86b935726..3f9e8bc0f 100644
--- a/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
+++ b/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
@@ -5,6 +5,7 @@ using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Domain.Common;
using Grand.Domain.Orders;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Commands.Models.Orders;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
@@ -20,6 +21,7 @@ using Microsoft.Extensions.DependencyInjection;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class MerchandiseReturnController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/NewsController.cs b/src/Web/Grand.Web/Controllers/NewsController.cs
index 379c117c9..3efd252fb 100644
--- a/src/Web/Grand.Web/Controllers/NewsController.cs
+++ b/src/Web/Grand.Web/Controllers/NewsController.cs
@@ -16,9 +16,11 @@ using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
+using Grand.SharedKernel.Attributes;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class NewsController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/NewsletterController.cs b/src/Web/Grand.Web/Controllers/NewsletterController.cs
index 7498e30b6..8a8077185 100644
--- a/src/Web/Grand.Web/Controllers/NewsletterController.cs
+++ b/src/Web/Grand.Web/Controllers/NewsletterController.cs
@@ -1,4 +1,5 @@
-using Grand.Web.Commands.Models.Newsletter;
+using Grand.SharedKernel.Attributes;
+using Grand.Web.Commands.Models.Newsletter;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Models.Newsletter;
@@ -8,6 +9,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class NewsletterController : BasePublicController
{
private readonly IMediator _mediator;
diff --git a/src/Web/Grand.Web/Controllers/OrderController.cs b/src/Web/Grand.Web/Controllers/OrderController.cs
index 9389fb718..71f3429f4 100644
--- a/src/Web/Grand.Web/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web/Controllers/OrderController.cs
@@ -10,6 +10,7 @@ using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Domain.Shipping;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Commands.Models.Orders;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
@@ -25,6 +26,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class OrderController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs b/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
index 972c2ca79..e54281bf0 100644
--- a/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
+++ b/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
@@ -6,6 +6,7 @@ using Grand.Domain.Catalog;
using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Features.Models.ShoppingCart;
@@ -16,6 +17,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
[DenySystemAccount]
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class OutOfStockSubscriptionController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/PageController.cs b/src/Web/Grand.Web/Controllers/PageController.cs
index 4564cfcc2..921699cfc 100644
--- a/src/Web/Grand.Web/Controllers/PageController.cs
+++ b/src/Web/Grand.Web/Controllers/PageController.cs
@@ -1,6 +1,7 @@
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Permissions;
+using Grand.SharedKernel.Attributes;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
using Grand.Web.Features.Models.Pages;
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class PageController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.cs
index 5f8b98337..74e27182a 100644
--- a/src/Web/Grand.Web/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web/Controllers/ProductController.cs
@@ -23,9 +23,11 @@ using Grand.Web.Features.Models.Products;
using Grand.Web.Models.Catalog;
using MediatR;
using Microsoft.AspNetCore.Mvc;
+using Grand.SharedKernel.Attributes;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class ProductController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
index 5a0578576..2a5dbc592 100644
--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
@@ -27,6 +27,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class ShoppingCartController : BasePublicController
{
#region Constructors
diff --git a/src/Web/Grand.Web/Controllers/VendorController.cs b/src/Web/Grand.Web/Controllers/VendorController.cs
index b4c02297d..82e4fff3b 100644
--- a/src/Web/Grand.Web/Controllers/VendorController.cs
+++ b/src/Web/Grand.Web/Controllers/VendorController.cs
@@ -1,5 +1,4 @@
-using Grand.Business.Core.Extensions;
-using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Customers;
@@ -8,9 +7,9 @@ using Grand.Business.Core.Interfaces.Storage;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
-using Grand.Domain.Seo;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.SharedKernel.Extensions;
using Grand.Web.Commands.Models.Vendors;
using Grand.Web.Common.Controllers;
@@ -22,10 +21,10 @@ using Grand.Web.Features.Models.Common;
using Grand.Web.Models.Vendors;
using MediatR;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.DependencyInjection;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class VendorController : BasePublicController
{
#region Constructors
@@ -210,7 +209,9 @@ public class VendorController : BasePublicController
if (ModelState.IsValid)
{
model = await _mediator.Send(new ContactVendorSendCommand {
- Model = model, Vendor = vendor, Store = _workContextAccessor.WorkContext.CurrentStore,
+ Model = model,
+ Vendor = vendor,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString()
});
return Json(model);
diff --git a/src/Web/Grand.Web/Controllers/WishlistController.cs b/src/Web/Grand.Web/Controllers/WishlistController.cs
index 7c47b24b6..7aef63aef 100644
--- a/src/Web/Grand.Web/Controllers/WishlistController.cs
+++ b/src/Web/Grand.Web/Controllers/WishlistController.cs
@@ -4,9 +4,10 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Utilities.Checkout;
-using Grand.Domain.Permissions;
using Grand.Domain.Orders;
+using Grand.Domain.Permissions;
using Grand.Infrastructure;
+using Grand.SharedKernel.Attributes;
using Grand.SharedKernel.Extensions;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
@@ -19,6 +20,7 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Controllers;
+[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)]
public class WishlistController : BasePublicController
{
#region Constructors
@@ -138,7 +140,8 @@ public class WishlistController : BasePublicController
warnings = ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage)).ToList();
}
- return Json(new {
+ return Json(new
+ {
success = !warnings.Any(),
warnings = string.Join(", ", warnings),
totalproducts =