Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Add Aspire project (#560)
Krzysztof Pajak9aa2ccc5b2d5
diff --git a/.github/workflows/aspnetcore.yml b/.github/workflows/aspnetcore.ymlindex add9565bc..57fceeeb5 100644--- a/.github/workflows/aspnetcore.yml+++ b/.github/workflows/aspnetcore.yml@@ -13,6 +13,8 @@ jobs:uses: actions/setup-dotnet@v4with:dotnet-version: 9.0.x+ - name: Install .NET Aspire workload+ run: dotnet workload install aspire- name: Restorerun: dotnet restore ./GrandNode.sln- name: Build with dotnetdiff --git a/.github/workflows/grandnode.yml b/.github/workflows/grandnode.ymlindex bfb14775b..cf725c1f9 100644--- a/.github/workflows/grandnode.yml+++ b/.github/workflows/grandnode.yml@@ -20,6 +20,8 @@ jobs:dotnet-version: 9.0.x- name: Create mongoDB Docker containerrun: sudo docker run -d -p 27017:27017 mongo:latest+ - name: Install .NET Aspire workload+ run: dotnet workload install aspire- name: Restorerun: dotnet restore "${{ env.WORKING_DIRECTORY }}"- name: Build slndiff --git a/Directory.Packages.props b/Directory.Packages.propsindex ff913ef39..0c63154f9 100644--- a/Directory.Packages.props+++ b/Directory.Packages.props@@ -64,5 +64,14 @@<PackageVersion Include="MSTest.TestFramework" Version="3.6.4" /><PackageVersion Include="coverlet.collector" Version="6.0.2" /><PackageVersion Include="NUnit" Version="4.2.2" />+ <PackageVersion Include="Aspire.Hosting.AppHost" Version="9.0.0" />+ <PackageVersion Include="Aspire.Hosting.MongoDB" Version="9.0.0" />+ <PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0" />+ <PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0" />+ <PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />+ <PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />+ <PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />+ <PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />+ <PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" /></ItemGroup></Project>\ No newline at end of filediff --git a/GrandNode.sln b/GrandNode.slnindex 1c8ca9b46..964782589 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -137,6 +137,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Module.Api", "src\ModEndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Module.ScheduledTasks", "src\Modules\Grand.Module.ScheduledTasks\Grand.Module.ScheduledTasks.csproj", "{136F1E35-8B20-465C-8D42-30A5A0D0DA1F}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.AppHost", "src\Aspire\Aspire.AppHost\Aspire.AppHost.csproj", "{FFA85947-690E-496B-B21E-DB1800F0DCA9}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aspire.ServiceDefaults", "src\Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj", "{591950E4-6377-4ECA-A386-8BD3FFE302F1}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -363,6 +367,14 @@ Global{136F1E35-8B20-465C-8D42-30A5A0D0DA1F}.Debug|Any CPU.Build.0 = Debug|Any CPU{136F1E35-8B20-465C-8D42-30A5A0D0DA1F}.Release|Any CPU.ActiveCfg = Release|Any CPU{136F1E35-8B20-465C-8D42-30A5A0D0DA1F}.Release|Any CPU.Build.0 = Release|Any CPU+ {FFA85947-690E-496B-B21E-DB1800F0DCA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {FFA85947-690E-496B-B21E-DB1800F0DCA9}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {FFA85947-690E-496B-B21E-DB1800F0DCA9}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {FFA85947-690E-496B-B21E-DB1800F0DCA9}.Release|Any CPU.Build.0 = Release|Any CPU+ {591950E4-6377-4ECA-A386-8BD3FFE302F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {591950E4-6377-4ECA-A386-8BD3FFE302F1}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {591950E4-6377-4ECA-A386-8BD3FFE302F1}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {591950E4-6377-4ECA-A386-8BD3FFE302F1}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSEdiff --git a/azure-pipelines.yml b/azure-pipelines.ymlindex 7ba85cf58..3946ed296 100644--- a/azure-pipelines.yml+++ b/azure-pipelines.yml@@ -1,18 +1,3 @@-# ASP.NET Core--# Build and test ASP.NET Core projects targeting .NET Core.-# Add steps that run tests, create a NuGet package, deploy, and more:-# https://docs.microsoft.com/azure/devops/pipelines/languages/dotnet-core--trigger:-- main--pool:- vmImage: ubuntu-latest--variables:- buildConfiguration: 'Release'-resources:containers:- container: mongo@@ -25,10 +10,15 @@ services:steps:- task: UseDotNet@2- displayName: 'Install .NET Core SDK 8'+ displayName: 'Install .NET Core SDK 9'inputs:version: '9.0.x'+- task: Install .NET Aspire workload+ inputs:+ inlineScript: |+ dotnet workload install aspire+- task: NuGetToolInstaller@1displayName: 'Install NuGet >=6.3.0-0'inputs:@@ -37,7 +27,7 @@ steps:- task: NuGetCommand@2inputs:- command: 'restore'+ command: 'restore'restoreSolution: '**/*.sln'feedsToUse: 'select'@@ -69,7 +59,4 @@ steps:arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)'zipAfterPublish: True-- task: PublishPipelineArtifact@1- inputs:- targetPath: '$(Build.ArtifactStagingDirectory)'- artifactName: 'grandnode'+- task: PublishPipelineArtifact@1\ No newline at end of filediff --git a/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj b/src/Aspire/Aspire.AppHost/Aspire.AppHost.csprojnew file mode 100644index 000000000..ffcf2a3ee--- /dev/null+++ b/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj@@ -0,0 +1,25 @@+<Project Sdk="Microsoft.NET.Sdk">++ <Sdk Name="Aspire.AppHost.Sdk" Version="9.0.0" />++ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net9.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsAspireHost>true</IsAspireHost>+ <UserSecretsId>bdc1e5b4-4475-44fc-851c-dd576ac2c123</UserSecretsId>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Aspire.Hosting.AppHost" />+ <PackageReference Include="Aspire.Hosting.MongoDB" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Web\Grand.Web.Admin\Grand.Web.Admin.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web.Vendor\Grand.Web.Vendor.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web\Grand.Web.csproj" />+ </ItemGroup>++</Project>diff --git a/src/Aspire/Aspire.AppHost/Program.cs b/src/Aspire/Aspire.AppHost/Program.csnew file mode 100644index 000000000..be68c9585--- /dev/null+++ b/src/Aspire/Aspire.AppHost/Program.cs@@ -0,0 +1,9 @@+using Aspire.AppHost;++var builder = DistributedApplication.CreateBuilder(args);++var mongo = builder.AddMongoDB("mongo").WithLifetime(ContainerLifetime.Persistent);+var mongodb = mongo.AddDatabase("Mongodb");+builder.ConfigureGrandWebProject(mongodb);++builder.Build().Run();diff --git a/src/Aspire/Aspire.AppHost/ProjectConfiguration.cs b/src/Aspire/Aspire.AppHost/ProjectConfiguration.csnew file mode 100644index 000000000..5f8053133--- /dev/null+++ b/src/Aspire/Aspire.AppHost/ProjectConfiguration.cs@@ -0,0 +1,13 @@+namespace Aspire.AppHost;++public static class ProjectConfiguration+{+ public static void ConfigureGrandWebProject(this IDistributedApplicationBuilder builder, IResourceBuilder<MongoDBDatabaseResource> mongodb)+ {+ builder+ .AddProject<Projects.Grand_Web>("grand-web")+ .WithHttpEndpoint(80, name: "front")+ .WithReference(mongodb)+ .WaitFor(mongodb);+ }+}\ No newline at end of filediff --git a/src/Aspire/Aspire.AppHost/Properties/launchSettings.json b/src/Aspire/Aspire.AppHost/Properties/launchSettings.jsonnew file mode 100644index 000000000..43ec3ebbe--- /dev/null+++ b/src/Aspire/Aspire.AppHost/Properties/launchSettings.json@@ -0,0 +1,32 @@+{+ "$schema": "https://json.schemastore.org/launchsettings.json",+ "profiles": {+ "https": {+ "commandName": "Project",+ "dotnetRunMessages": true,+ "launchBrowser": true,+ "applicationUrl": "https://localhost:17196;http://localhost:15129",+ "environmentVariables": {+ "ASPNETCORE_ENVIRONMENT": "Development",+ "DOTNET_ENVIRONMENT": "Development",+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21225",+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22257",+ "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"+ }+ },+ "http": {+ "commandName": "Project",+ "dotnetRunMessages": true,+ "launchBrowser": true,+ "applicationUrl": "http://localhost:15129",+ "environmentVariables": {+ "ASPNETCORE_ENVIRONMENT": "Development",+ "DOTNET_ENVIRONMENT": "Development",+ "DOTNET_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19032",+ "DOTNET_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20163",+ "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true"++ }+ }+ }+}diff --git a/src/Aspire/Aspire.AppHost/appsettings.Development.json b/src/Aspire/Aspire.AppHost/appsettings.Development.jsonnew file mode 100644index 000000000..0c208ae91--- /dev/null+++ b/src/Aspire/Aspire.AppHost/appsettings.Development.json@@ -0,0 +1,8 @@+{+ "Logging": {+ "LogLevel": {+ "Default": "Information",+ "Microsoft.AspNetCore": "Warning"+ }+ }+}diff --git a/src/Aspire/Aspire.AppHost/appsettings.json b/src/Aspire/Aspire.AppHost/appsettings.jsonnew file mode 100644index 000000000..31c092aa4--- /dev/null+++ b/src/Aspire/Aspire.AppHost/appsettings.json@@ -0,0 +1,9 @@+{+ "Logging": {+ "LogLevel": {+ "Default": "Information",+ "Microsoft.AspNetCore": "Warning",+ "Aspire.Hosting.Dcp": "Warning"+ }+ }+}diff --git a/src/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj b/src/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csprojnew file mode 100644index 000000000..f6cb4c09d--- /dev/null+++ b/src/Aspire/Aspire.ServiceDefaults/Aspire.ServiceDefaults.csproj@@ -0,0 +1,22 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFramework>net9.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsAspireSharedProject>true</IsAspireSharedProject>+ </PropertyGroup>++ <ItemGroup>+ <FrameworkReference Include="Microsoft.AspNetCore.App" />++ <PackageReference Include="Microsoft.Extensions.Http.Resilience" />+ <PackageReference Include="Microsoft.Extensions.ServiceDiscovery" />+ <PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />+ <PackageReference Include="OpenTelemetry.Extensions.Hosting" />+ <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />+ <PackageReference Include="OpenTelemetry.Instrumentation.Http" />+ <PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />+ </ItemGroup>++</Project>diff --git a/src/Aspire/Aspire.ServiceDefaults/Extensions.cs b/src/Aspire/Aspire.ServiceDefaults/Extensions.csnew file mode 100644index 000000000..d5cfd5122--- /dev/null+++ b/src/Aspire/Aspire.ServiceDefaults/Extensions.cs@@ -0,0 +1,89 @@+using Microsoft.AspNetCore.Builder;+using Microsoft.AspNetCore.Diagnostics.HealthChecks;+using Microsoft.Extensions.DependencyInjection;+using Microsoft.Extensions.Diagnostics.HealthChecks;+using Microsoft.Extensions.Logging;+using Microsoft.Extensions.ServiceDiscovery;+using OpenTelemetry;+using OpenTelemetry.Metrics;+using OpenTelemetry.Trace;++namespace Microsoft.Extensions.Hosting;++// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry.+// This project should be referenced by each service project in your solution.+// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults+public static class Extensions+{+ public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder+ {+ builder.ConfigureOpenTelemetry();++ builder.Services.AddServiceDiscovery();++ builder.Services.ConfigureHttpClientDefaults(http =>+ {+ // Turn on resilience by default+ http.AddStandardResilienceHandler();++ // Turn on service discovery by default+ http.AddServiceDiscovery();+ });++ // Uncomment the following to restrict the allowed schemes for service discovery.+ // builder.Services.Configure<ServiceDiscoveryOptions>(options =>+ // {+ // options.AllowedSchemes = ["https"];+ // });++ return builder;+ }++ public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder+ {+ builder.Logging.AddOpenTelemetry(logging =>+ {+ logging.IncludeFormattedMessage = true;+ logging.IncludeScopes = true;+ });++ builder.Services.AddOpenTelemetry()+ .WithMetrics(metrics =>+ {+ metrics.AddAspNetCoreInstrumentation()+ .AddHttpClientInstrumentation()+ .AddRuntimeInstrumentation();+ })+ .WithTracing(tracing =>+ {+ tracing.AddSource(builder.Environment.ApplicationName)+ .AddAspNetCoreInstrumentation()+ // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)+ //.AddGrpcClientInstrumentation()+ .AddHttpClientInstrumentation();+ });++ builder.AddOpenTelemetryExporters();++ return builder;+ }++ private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder+ {+ var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);++ if (useOtlpExporter)+ {+ builder.Services.AddOpenTelemetry().UseOtlpExporter();+ }++ // Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)+ //if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))+ //{+ // builder.Services.AddOpenTelemetry()+ // .UseAzureMonitor();+ //}++ return builder;+ }+}diff --git a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.csindex c2396e529..6bb260554 100644--- a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs@@ -16,11 +16,4 @@ public class DatabaseConfig/// Gets or sets a value indicating whether use LiteDB database (only for installation process)/// </summary>public string LiteDbConnectionString { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether use connection string for database (only for installed databases)- /// </summary>- public string ConnectionString { get; set; }-- public int DbProvider { get; set; }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs b/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.csindex 6597c5aac..b95260ea8 100644--- a/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs@@ -10,11 +10,6 @@ public class PerformanceConfig/// </summary>public bool UseResponseCompression { get; set; }- /// <summary>- /// Gets or sets a value indicating whether ignore DbVersionCheckMiddleware- /// </summary>- public bool IgnoreDbVersionCheckMiddleware { get; set; }-/// <summary>/// Gets or sets a value indicating whether ignore IgnoreUsePoweredByMiddleware/// </summary>diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.csindex 70e0d350a..11a4af331 100644--- a/src/Core/Grand.Infrastructure/StartupBase.cs+++ b/src/Core/Grand.Infrastructure/StartupBase.cs@@ -36,11 +36,18 @@ public static class StartupBase/// </summary>private static void InitDatabase(IServiceCollection services, IConfiguration configuration){- var dbConfig = services.StartupConfig<DatabaseConfig>(configuration.GetSection("Database"));- if (!string.IsNullOrEmpty(dbConfig.ConnectionString))+ var connectionString = configuration[SettingsConstants.ConnectionStrings];+ var providerString = configuration[SettingsConstants.ConnectionStringsProvider];+ var providerInt = 0;+ if (!string.IsNullOrEmpty(providerString))+ {+ _ = int.TryParse(providerString, out providerInt);+ }++ if (!string.IsNullOrEmpty(connectionString))DataSettingsManager.Instance.LoadDataSettings(new DataSettings {- ConnectionString = dbConfig.ConnectionString,- DbProvider = (DbProvider)dbConfig.DbProvider+ ConnectionString = connectionString,+ DbProvider = (DbProvider)providerInt,});}diff --git a/src/Core/Grand.SharedKernel/Extensions/SettingsConstants.cs b/src/Core/Grand.SharedKernel/Extensions/SettingsConstants.csnew file mode 100644index 000000000..f343400c0--- /dev/null+++ b/src/Core/Grand.SharedKernel/Extensions/SettingsConstants.cs@@ -0,0 +1,7 @@+namespace Grand.SharedKernel.Extensions;++public static class SettingsConstants+{+ public const string ConnectionStrings = "ConnectionStrings:Mongodb";+ public const string ConnectionStringsProvider = "ConnectionStrings:Provider";+}diff --git a/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs b/src/Modules/Grand.Module.Installer/Controllers/InstallController.csindex 5ab7da3b6..b06dc9c8b 100644--- a/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs+++ b/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs@@ -2,13 +2,13 @@using Grand.Infrastructure.Caching;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Plugins;-using Grand.Module.Installer.Filters;using Grand.Module.Installer.Interfaces;using Grand.Module.Installer.Models;using Grand.SharedKernel.Extensions;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Rendering;+using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;@@ -16,7 +16,6 @@ using MongoDB.Driver;namespace Grand.Module.Installer.Controllers;-[DatabaseConfigured]public class InstallController : Controller{@@ -25,6 +24,7 @@ public class InstallController : Controllerprivate readonly ICacheBase _cacheBase;private readonly IHostApplicationLifetime _applicationLifetime;private readonly DatabaseConfig _dbConfig;+ private readonly IConfiguration _configuration;private readonly ILogger<InstallController> _logger;/// <summary>@@ -40,11 +40,13 @@ public class InstallController : ControllerICacheBase cacheBase,IHostApplicationLifetime applicationLifetime,DatabaseConfig dbConfig,+ IConfiguration configuration,ILogger<InstallController> logger){_cacheBase = cacheBase;_applicationLifetime = applicationLifetime;_dbConfig = dbConfig;+ _configuration = configuration;_logger = logger;}@@ -70,11 +72,15 @@ public class InstallController : Controllermodel ??= new InstallModel {AdminEmail = "[email protected]",InstallSampleData = false,- DatabaseConnectionString = "",AdminPassword = "",ConfirmPassword = ""};+ if (!string.IsNullOrEmpty(_configuration[SettingsConstants.ConnectionStrings]))+ {+ model.SkipConnection = true;+ }+model.AvailableProviders = Enum.GetValues(typeof(DbProvider)).Cast<DbProvider>().Select(v => new SelectListItem {Text = v.ToString(),Value = ((int)v).ToString()@@ -192,7 +198,7 @@ public class InstallController : Controllerelse if (string.IsNullOrEmpty(connectionString))ModelState.AddModelError("", locService.GetResource(model.SelectedLanguage, "ConnectionStringRequired"));}-+[HttpPost]public virtual async Task<IActionResult> Index(InstallModel model){@@ -205,9 +211,11 @@ public class InstallController : Controllerif (model.DatabaseConnectionString != null)model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();- var connectionString = BuildConnectionString(locService, model);+ var connectionString = !string.IsNullOrEmpty(_configuration[SettingsConstants.ConnectionStrings]) ?+ _configuration[SettingsConstants.ConnectionStrings]:+ BuildConnectionString(locService, model);- await CheckConnectionString(locService, connectionString, model);+ await CheckConnectionString(locService, connectionString!, model);if (!ModelState.IsValid) return View(PrepareModel(model));try@@ -217,9 +225,11 @@ public class InstallController : ControllerConnectionString = connectionString,DbProvider = model.DataProvider};-- await DataSettingsManager.Instance.SaveSettings(settings);- DataSettingsManager.Instance.LoadSettings(true);+ if (string.IsNullOrEmpty(_configuration[SettingsConstants.ConnectionStrings]))+ {+ await DataSettingsManager.Instance.SaveSettings(settings);+ DataSettingsManager.Instance.LoadSettings(true);+ }var installationService = HttpContext.RequestServices.GetRequiredService<IInstallationService>();await installationService.InstallData(diff --git a/src/Modules/Grand.Module.Installer/Filters/DatabaseConfiguredAttribute.cs b/src/Modules/Grand.Module.Installer/Filters/DatabaseConfiguredAttribute.csdeleted file mode 100644index d4319211c..000000000--- a/src/Modules/Grand.Module.Installer/Filters/DatabaseConfiguredAttribute.cs+++ /dev/null@@ -1,20 +0,0 @@-using Grand.Data;-using Microsoft.AspNetCore.Mvc;-using Microsoft.AspNetCore.Mvc.Filters;--namespace Grand.Module.Installer.Filters;--public class DatabaseConfiguredAttribute : Attribute, IAsyncActionFilter-{- public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)- {- if (!DataSettingsManager.DatabaseIsInstalled())- {- await next();- }- else- {- context.Result = new NotFoundResult();- }- }-}diff --git a/src/Modules/Grand.Module.Installer/Models/InstallModel.cs b/src/Modules/Grand.Module.Installer/Models/InstallModel.csindex e0bb8692b..1c8435322 100644--- a/src/Modules/Grand.Module.Installer/Models/InstallModel.cs+++ b/src/Modules/Grand.Module.Installer/Models/InstallModel.cs@@ -20,6 +20,7 @@ public class InstallModel : BaseModelpublic string? DatabaseConnectionString { get; set; }public DbProvider DataProvider { get; set; }+ public bool SkipConnection { get; set; }public bool ConnectionInfo { get; set; }public string? MongoDBServerName { get; set; }public string? MongoDBDatabaseName { get; set; }diff --git a/src/Modules/Grand.Module.Installer/Services/DatabaseFactoryContext.cs b/src/Modules/Grand.Module.Installer/Services/DatabaseFactoryContext.csindex 991f06e43..984f41663 100644--- a/src/Modules/Grand.Module.Installer/Services/DatabaseFactoryContext.cs+++ b/src/Modules/Grand.Module.Installer/Services/DatabaseFactoryContext.cs@@ -11,7 +11,7 @@ public class DatabaseFactoryContext : IDatabaseFactoryContextpublic IDatabaseContext GetDatabaseContext(string? connectionString = null, DbProvider? dbProvider = null){var dataSettings = string.IsNullOrEmpty(connectionString) ? DataSettingsManager.Instance.LoadSettings(true) :- new DataSettings() { ConnectionString = connectionString, DbProvider = dbProvider!.Value };+ new DataSettings() { ConnectionString = connectionString, DbProvider = dbProvider.HasValue ? dbProvider.Value : DbProvider.MongoDB };if (dataSettings != null && !string.IsNullOrEmpty(dataSettings.ConnectionString)){if (dataSettings.DbProvider != DbProvider.LiteDB)diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.csindex e35a98db4..018df5244 100644--- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs+++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs@@ -34,6 +34,7 @@ using Grand.SharedKernel;using Grand.SharedKernel.Extensions;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;+using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using System.Security.Cryptography;@@ -1006,8 +1007,9 @@ public partial class InstallationService : IInstallationServicetry{+ var configuration = _serviceProvider.GetRequiredService<IConfiguration>();var dataSettings = DataSettingsManager.Instance.LoadSettings(true);- var dbContext = _serviceProvider.GetRequiredService<IDatabaseFactoryContext>().GetDatabaseContext();+ var dbContext = _serviceProvider.GetRequiredService<IDatabaseFactoryContext>().GetDatabaseContext(configuration[SettingsConstants.ConnectionStrings]);if (dataSettings.DbProvider != DbProvider.LiteDB){var typeSearcher = _serviceProvider.GetRequiredService<ITypeSearcher>();@@ -1016,10 +1018,9 @@ public partial class InstallationService : IInstallationServiceforeach (var item in q!.GetTypes())if (item.BaseType != null && item.IsClass && item.BaseType == typeof(BaseEntity))await dbContext.CreateTable(item.Name, local);- }- if (dataSettings.DbProvider != DbProvider.LiteDB)await CreateIndexes(dbContext, dataSettings);+ }}catch (Exception ex){diff --git a/src/Modules/Grand.Module.Installer/Startup/EndpointProvider.cs b/src/Modules/Grand.Module.Installer/Startup/EndpointProvider.csnew file mode 100644index 000000000..9cbe4d7f7--- /dev/null+++ b/src/Modules/Grand.Module.Installer/Startup/EndpointProvider.cs@@ -0,0 +1,15 @@+using Grand.Infrastructure.Endpoints;+using Microsoft.AspNetCore.Builder;+using Microsoft.AspNetCore.Routing;++namespace Grand.Module.Installer.Startup;++public class EndpointProvider : IEndpointProvider+{+ public int Priority => int.MinValue;++ public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)+ {+ endpointRouteBuilder.MapControllerRoute("Install", "install", new { controller = "Install", action = "Index" });+ }+}diff --git a/src/Modules/Grand.Module.Installer/Startup/StartupApplication.cs b/src/Modules/Grand.Module.Installer/Startup/StartupApplication.csindex 132744ee9..94a44092a 100644--- a/src/Modules/Grand.Module.Installer/Startup/StartupApplication.cs+++ b/src/Modules/Grand.Module.Installer/Startup/StartupApplication.cs@@ -1,5 +1,4 @@-using Grand.Data;-using Grand.Infrastructure;+using Grand.Infrastructure;using Grand.Module.Installer.Interfaces;using Grand.Module.Installer.Services;using Microsoft.AspNetCore.Builder;@@ -25,13 +24,8 @@ public class StartupApplication : IStartupApplicationprivate void RegisterInstallService(IServiceCollection serviceCollection){- var databaseInstalled = DataSettingsManager.DatabaseIsInstalled();- if (!databaseInstalled)- {- //installation service- serviceCollection.AddScoped<IInstallationLocalizedService, InstallationLocalizedService>();- serviceCollection.AddScoped<IInstallationService, InstallationService>();- serviceCollection.AddTransient<IDatabaseFactoryContext, DatabaseFactoryContext>();- }+ serviceCollection.AddScoped<IInstallationLocalizedService, InstallationLocalizedService>();+ serviceCollection.AddScoped<IInstallationService, InstallationService>();+ serviceCollection.AddTransient<IDatabaseFactoryContext, DatabaseFactoryContext>();}}\ No newline at end of filediff --git a/src/Modules/Grand.Module.Installer/Views/Install/Index.cshtml b/src/Modules/Grand.Module.Installer/Views/Install/Index.cshtmlindex 67bf6b696..0f0222d35 100644--- a/src/Modules/Grand.Module.Installer/Views/Install/Index.cshtml+++ b/src/Modules/Grand.Module.Installer/Views/Install/Index.cshtml@@ -15,177 +15,191 @@<script src="@Url.Content("~/assets/install/install.js")"></script></head><body class="install-wrapper">-<div class="container">-@if (!Model.Installed)-{- <form asp-action="Index" asp-controller="Install" id="installation-form" method="post" autocomplete="off">- <div class="row flex-row">- <div class="col-xl-5 col-lg-6 col-md-12 logo-container">- <img class="img-fluid" title="" alt="grandNode" src="~/logo.png"/>- </div>- <div class="col-xl-7 col-lg-6 col-md-12">- <div class="row">- <div class="col-md">- <h1 class="generalTitle">@LocalizedService.GetResource(Model.SelectedLanguage, "Title")</h1>- </div>- <div class="col-md-3 col-5 pt-3">- @Html.DropDownList("language", Model.AvailableLanguages, new { @class = "custom-select", onchange = "window.location.href = this.value;" })- </div>- </div>- </div>- </div>- <div class="content">- <p>- @LocalizedService.GetResource(Model.SelectedLanguage, "Tooltip2")- <div style="color: Red;">- @Html.ValidationSummary(false)- </div>- </p>- </div>- <div class="card">- <a href="https://bit.ly/3cD1drT" target="_blank">- <img class="img-fluid" title="" alt="GrandNode Support Services" src="~/banner.jpg"/>- </a>- </div>- <div class="card">- <h3 class="card-header">- @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyInformation")- </h3>- <div class="card-body">-- <div class="row">- <div class="col-md-6 col-12">- <label for="AdminPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyName"):- </label>- <input asp-for="CompanyName" class="form-control"/>+ <div class="container">+ @if (!Model.Installed)+ {+ <form asp-action="Index" asp-controller="Install" id="installation-form" method="post" autocomplete="off">+ <div class="row flex-row">+ <div class="col-xl-5 col-lg-6 col-md-12 logo-container">+ <img class="img-fluid" title="" alt="grandNode" src="~/logo.png"/></div>- <div class="col-md-6">- <label for="ConfirmPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyAddress"):- </label>- <input asp-for="CompanyAddress" class="form-control"/>+ <div class="col-xl-7 col-lg-6 col-md-12">+ <div class="row">+ <div class="col-md">+ <h1 class="generalTitle">@LocalizedService.GetResource(Model.SelectedLanguage, "Title")</h1>+ </div>+ <div class="col-md-3 col-5 pt-3">+ @Html.DropDownList("language", Model.AvailableLanguages, new { @class = "custom-select", onchange = "window.location.href = this.value;" })+ </div>+ </div></div></div>- <div class="row">- <div class="col-md-6 col-12">- <label for="AdminPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyPhoneNumber"):- </label>- <input asp-for="CompanyPhoneNumber" class="form-control"/>- </div>- <div class="col-md-6">- <label for="ConfirmPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyEmail"):- </label>- <input asp-for="CompanyEmail" class="form-control"/>- </div>+ <div class="content">+ <p>+ @LocalizedService.GetResource(Model.SelectedLanguage, "Tooltip2")+ <div style="color: Red;">+ @Html.ValidationSummary(false)+ </div>+ </p></div>- </div>- </div>- <div class="card">- <h3 class="card-header">- @LocalizedService.GetResource(Model.SelectedLanguage, "StoreInformation")- </h3>- <div class="card-body">- <label for="AdminEmail" class="col-form-label">- @LocalizedService.GetResource(Model.SelectedLanguage, "AdminEmail"):- </label>- <input asp-for="AdminEmail" class="form-control" required/>- <div class="row">- <div class="col-md-6 col-12">- <label for="AdminPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "AdminPassword"):- </label>- <input asp-for="AdminPassword" class="form-control password" required/>- </div>- <div class="col-md-6">- <label for="ConfirmPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "ConfirmPassword"):- </label>- <input asp-for="ConfirmPassword" class="form-control password" required/>- </div>+ <div class="card">+ <a href="https://bit.ly/3cD1drT" target="_blank">+ <img class="img-fluid" title="" alt="GrandNode Support Services" src="~/banner.jpg"/>+ </a></div>- </div>- </div>- <div class="card">- <h3 class="card-header">- @LocalizedService.GetResource(Model.SelectedLanguage, "DataProvider")- </h3>- <div class="card-body">- @Html.DropDownList("DataProvider", Model.AvailableProviders, new { @class = "custom-select", onchange = "DataProviderChange(this.value);" })- </div>- </div>- @if (!Model.DisableSampleDataOption)- {- <div nowrap="nowrap" align="left">- <label class="custom-control custom-checkbox my-3">- <input asp-for="InstallSampleData" class="custom-control-input"/>- <span class="custom-control-label"></span>- <span class="custom-control-description">@LocalizedService.GetResource(Model.SelectedLanguage, "CreateSampleData")</span>- </label>- </div>- }- <section id="ConnectionInformation">- <div id="DBSampleData"><div class="card"><h3 class="card-header">- @LocalizedService.GetResource(Model.SelectedLanguage, "DatabaseInformation")+ @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyInformation")</h3><div class="card-body">- <label for="MongoDBServerName">- @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBServerName"):- </label>- <input asp-for="MongoDBServerName" class="form-control"/>- <div class="row mongoDBDatabaseName">- <div class="col-6">- <label for="MongoDBDatabaseName">- @LocalizedService.GetResource(Model.SelectedLanguage, "DatabaseName"):++ <div class="row">+ <div class="col-md-6 col-12">+ <label for="AdminPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyName"):</label>- <input asp-for="MongoDBDatabaseName" class="form-control"/>+ <input asp-for="CompanyName" class="form-control"/></div>- <div class="col-6 collation" id="collation">- <label for="Collation">- @LocalizedService.GetResource(Model.SelectedLanguage, "Collation"):+ <div class="col-md-6">+ <label for="ConfirmPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyAddress"):</label>- @Html.DropDownList("Collation", Model.AvailableCollation, new { @class = "custom-select" })+ <input asp-for="CompanyAddress" class="form-control"/></div></div><div class="row">- <div class="col-6">- <label for="MongoDBUsername">- @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBUsername"):+ <div class="col-md-6 col-12">+ <label for="AdminPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyPhoneNumber"):</label>- <input asp-for="MongoDBUsername" class="form-control"/>+ <input asp-for="CompanyPhoneNumber" class="form-control"/></div>- <div class="col-6">- <label for="MongoDBPassword">- @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBPassword"):+ <div class="col-md-6">+ <label for="ConfirmPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "CompanyEmail"):</label>- <input asp-for="MongoDBPassword" class="form-control password"/>+ <input asp-for="CompanyEmail" class="form-control"/>+ </div>+ </div>+ </div>+ </div>+ <div class="card">+ <h3 class="card-header">+ @LocalizedService.GetResource(Model.SelectedLanguage, "StoreInformation")+ </h3>+ <div class="card-body">+ <label for="AdminEmail" class="col-form-label">+ @LocalizedService.GetResource(Model.SelectedLanguage, "AdminEmail"):+ </label>+ <input asp-for="AdminEmail" class="form-control" required/>+ <div class="row">+ <div class="col-md-6 col-12">+ <label for="AdminPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "AdminPassword"):+ </label>+ <input asp-for="AdminPassword" class="form-control password" required/>+ </div>+ <div class="col-md-6">+ <label for="ConfirmPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "ConfirmPassword"):+ </label>+ <input asp-for="ConfirmPassword" class="form-control password" required/>+ </div>+ </div>+ </div>+ </div>+ <div class="card">+ <h3 class="card-header">+ @LocalizedService.GetResource(Model.SelectedLanguage, "DataProvider")+ </h3>+ <div class="card-body">+ @Html.DropDownList("DataProvider", Model.AvailableProviders, new { @class = "custom-select", onchange = "DataProviderChange(this.value);" })+ </div>+ </div>+ @if (Model.SkipConnection)+ {+ <div class="card">+ <h3 class="card-header">+ @LocalizedService.GetResource(Model.SelectedLanguage, "Collation")+ </h3>+ <div class="card-body">+ @Html.DropDownList("Collation", Model.AvailableCollation, new { @class = "custom-select" })+ </div>+ </div>+ }+ @if (!Model.DisableSampleDataOption)+ {+ <div nowrap="nowrap" align="left">+ <label class="custom-control custom-checkbox my-3">+ <input asp-for="InstallSampleData" class="custom-control-input"/>+ <span class="custom-control-label"></span>+ <span class="custom-control-description">@LocalizedService.GetResource(Model.SelectedLanguage, "CreateSampleData")</span>+ </label>+ </div>+ }+ @if (!Model.SkipConnection)+ {+ <section id="ConnectionInformation">+ <div id="DBSampleData">+ <div class="card">+ <h3 class="card-header">+ @LocalizedService.GetResource(Model.SelectedLanguage, "DatabaseInformation")+ </h3>+ <div class="card-body">+ <label for="MongoDBServerName">+ @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBServerName"):+ </label>+ <input asp-for="MongoDBServerName" class="form-control"/>+ <div class="row mongoDBDatabaseName">+ <div class="col-6">+ <label for="MongoDBDatabaseName">+ @LocalizedService.GetResource(Model.SelectedLanguage, "DatabaseName"):+ </label>+ <input asp-for="MongoDBDatabaseName" class="form-control"/>+ </div>+ <div class="col-6 collation" id="collation">+ <label for="Collation">+ @LocalizedService.GetResource(Model.SelectedLanguage, "Collation"):+ </label>+ @Html.DropDownList("Collation", Model.AvailableCollation, new { @class = "custom-select" })+ </div>+ </div>+ <div class="row">+ <div class="col-6">+ <label for="MongoDBUsername">+ @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBUsername"):+ </label>+ <input asp-for="MongoDBUsername" class="form-control"/>+ </div>+ <div class="col-6">+ <label for="MongoDBPassword">+ @LocalizedService.GetResource(Model.SelectedLanguage, "MongoDBPassword"):+ </label>+ <input asp-for="MongoDBPassword" class="form-control password"/>+ </div></div></div></div></div>- </div>- <label class="custom-control custom-checkbox my-3">- <input asp-for="ConnectionInfo" onchange="toggleMongoDBConnectionInfo()" class="custom-control-input"/>- <span class="custom-control-label"></span>- <span class="custom-control-description">@LocalizedService.GetResource(Model.SelectedLanguage, "ConnectionString"):</span>- </label>- <div id="DatabaseConnectionString" class="connection-string-container" style="display:none;">- <span style="white-space: nowrap;">- <input asp-for="DatabaseConnectionString" class="textbox form-control"/>- </span>- <span class="hint">- @LocalizedService.GetResource(Model.SelectedLanguage, "Example"):<br/>- For MongoDB: @Html.Raw("mongodb+srv://<username>:<password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority")- (Find more info <a href="https://docs.mongodb.org/manual/reference/connection-string/" target="_blank">here</a>)- </span>- </div>- </section>+ <label class="custom-control custom-checkbox my-3">+ <input asp-for="ConnectionInfo" onchange="toggleMongoDBConnectionInfo()" class="custom-control-input"/>+ <span class="custom-control-label"></span>+ <span class="custom-control-description">@LocalizedService.GetResource(Model.SelectedLanguage, "ConnectionString"):</span>+ </label>+ <div id="DatabaseConnectionString" class="connection-string-container" style="display:none;">+ <span style="white-space: nowrap;">+ <input asp-for="DatabaseConnectionString" class="textbox form-control"/>+ </span>+ <span class="hint">+ @LocalizedService.GetResource(Model.SelectedLanguage, "Example"):<br/>+ For MongoDB: @Html.Raw("mongodb+srv://<username>:<password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority")+ (Find more info <a href="https://docs.mongodb.org/manual/reference/connection-string/" target="_blank">here</a>)+ </span>+ </div>+ </section>+ }<div class="row"><div class="col-12">@LocalizedService.GetResource(Model.SelectedLanguage, "Documentation1") <a href="https://docs.grandnode.com/" target="_blank">@LocalizedService.GetResource(Model.SelectedLanguage, "Documentation2")</a>.diff --git a/src/Modules/Grand.Module.Migration/Migrations/MigrationProcess.cs b/src/Modules/Grand.Module.Migration/Migrations/MigrationProcess.csindex 145c023e4..dfe9c79bd 100644--- a/src/Modules/Grand.Module.Migration/Migrations/MigrationProcess.cs+++ b/src/Modules/Grand.Module.Migration/Migrations/MigrationProcess.cs@@ -57,6 +57,8 @@ public class MigrationProcess : IMigrationProcess{var migrationsDb = GetMigrationDb();var version = _repositoryVersion.Table.FirstOrDefault();+ if(version == null)+ return;var majorVersion = string.IsNullOrEmpty(version?.InstalledVersion) ? int.Parse(version?.DataBaseVersion.Split('.')[0]!) : int.Parse(version?.InstalledVersion.Split('.')[0]!);var minorVersion = string.IsNullOrEmpty(version?.InstalledVersion) ? int.Parse(version?.DataBaseVersion.Split('.')[1]!) : int.Parse(version?.InstalledVersion.Split('.')[1]!);var migrationManager = new MigrationManager();diff --git a/src/Web/Grand.Web.Admin/App_Data/appsettings.json b/src/Web/Grand.Web.Admin/App_Data/appsettings.jsonindex 584b2b7bb..898c13214 100644--- a/src/Web/Grand.Web.Admin/App_Data/appsettings.json+++ b/src/Web/Grand.Web.Admin/App_Data/appsettings.json@@ -1,45 +1,45 @@{"Application": {-//Enable if you want to see the full error in production environment. It's ignored (always enabled) in development environment"DisplayFullErrorStack": true,-//Value of "Cache-Control" header value for static content"StaticFilesCacheControl": "public,max-age=31536000",-//Enable the session-based TempData provider"UseSessionStateTempDataProvider": false,-+ //A value indicating whether SEO friendly URLs with multiple languages are enabled+ "SeoFriendlyUrlsForLanguagesEnabled": false,+ "SeoFriendlyUrlsDefaultCode": "en",//Note: While use of custom response header encoding may be needed in some cases,//we discourage the use of non-ASCII encodings to avoid compatibility issues//with other HTTP clients."AllowNonAsciiCharInHeaders": false,-//Gets or sets the maximum allowed size of any request body in bytes//the default value is 30MB- "MaxRequestBodySize": null //max 2147483648- },+ "MaxRequestBodySize": null,+ //max 2147483648+ //Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore+ "EnableContextLoggingMiddleware": true+ },+ //only for advanced users, allow to set ConnectionString for MongoDb+ "ConnectionStrings": {+ "Mongodb": ""+ },"Database": {//This setting is required to use LiteDB database"UseLiteDb": false,//LiteDB database as a singleton service in the application"Singleton": true,//Init connection string - it's required only for the installation process!- "LiteDbConnectionString": "Filename=App_Data/database.db",- //only for advanced users, allow to set ConnectionString for MongoDb- "ConnectionString": "",- "DbProvider": 0+ "LiteDbConnectionString": "Filename=App_Data/database.db"},-"Security": {-//Use a reverse proxy server - more information you can find at: https://docs.microsoft.com/en-US/aspnet/core/host-and-deploy/linux-nginx"UseForwardedHeaders": false,-+ //In some cases, it might not be possible to add forwarded headers to the requests proxied to the app.+ "ForceUseHTTPS": false,//AllowedHosts, is used for host filtering to bind your app to specific hostnames"AllowedHosts": "*",-//This settings adds the following headers to all responses that pass//X-Content-Type-Options: nosniff//Strict-Transport-Security: max-age=31536000; includeSubDomains@@ -48,78 +48,72 @@//Referrer-Policy: strict-origin-when-cross-origin//Content-Security-Policy: object-src 'none'; form-action 'self'; frame-ancestors 'none'"UseDefaultSecurityHeaders": false,-//HTTP Strict Transport Security Protocol"UseHsts": false,-//When enabled, allow Razor files to be updated if they're edited.- "EnableRuntimeCompilation": true,-+ "EnableRuntimeCompilation": false,//We recommend all ASP.NET Core web apps call HTTPS Redirection Middleware to redirect all HTTP requests to HTTPS"UseHttpsRedirection": false,"HttpsRedirectionRedirect": 308,"HttpsRedirectionHttpsPort": 443,-//Key persistence location you can point to a directory on the local machine, or it can point to a folder on a network share.//if is null it will use the default directory path - ApplicationPath\App_Data\DataProtectionKeys- "KeyPersistenceLocation": null,-+ "KeyPersistenceLocation": "/App_Data/DataProtectionKeys",//Gets or sets a value indicating for cookie auth expires in hours - default 24 * 365 = 8760"CookieAuthExpires": 8760,-//Gets or sets a value for cookie prefix - any changes will log out all of the customers"CookiePrefix": ".Grand.",-//Gets or sets a value for cookie claim issuer - any changes will log out all of the customers"CookieClaimsIssuer": "grandnode",-//CookieSecurePolicy.Always always sets the Secure flag//Always setting the Secure flag is the most restrictive and most secure option.//This is the one you should be targeting if your production environment fully runs on HTTPS"CookieSecurePolicyAlways": false,-+ //Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks+ //Available values Unspecified, None, Lax, Strict+ "CookieSameSite": "Lax",+ "CookieSameSiteExternalAuth": "None",//Enabling this setting allows for verification of access to a specific controller and action in the admin panel using menu configuration."AuthorizeAdminMenu": false},-+ "Cache": {+ //Gets or sets a value indicating for default cache time in minutes"+ "DefaultCacheTimeMinutes": 60+ },"Extensions": {-//For developers - more info you can find at https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk///https://github.com/dotnet/roslyn/wiki/Roslyn-Overview"UseRoslynScripts": false,-- //Disable upload extensions plugins/themes+ //Disable upload extensions plugins"DisableUploadExtensions": false,-//A list of plugins to be ignored during start application - pattern"PluginSkipLoadingPattern": "",-//Enable if you want to clear /Plugins/bin directory on application startup"ClearPluginShadowDirectoryOnStartup": true,-//For develop you should enable if you want to copy plugin dll files to directory /Plugins/bin on application startup"PluginShadowCopy": true,+ //separator comma"InstalledPlugins": ""-- },- "Cache": {- //Gets or sets a value indicating for default cache time in minutes"- "DefaultCacheTimeMinutes": 60},"AccessControl": {/// A value indicating whether to ignore ACL rules"IgnoreAcl": false,-//A value indicating whether to ignore "limit per store" rules"IgnoreStoreLimitations": false},"Performance": {-//Indicates whether to compress response (gzip by default)//You may want to disable it, for example, If you have an active IIS Dynamic Compression Module configured at the server level- "UseResponseCompression": false+ "UseResponseCompression": false,+ //Indicates whether to ignore UsePoweredByMiddleware+ "IgnoreUsePoweredByMiddleware": false+ },+ "FeatureManagement": {+ "Grand.Module.Installer": false,+ "Grand.Module.Migration": false,+ "Grand.Module.ScheduledTasks": false,+ "Grand.Module.Api": false},-"Redis": {///Enable the Publish/Subscribe messaging with redis to manage memory cache on every server"RedisPubSubEnabled": false,@@ -128,7 +122,6 @@"PersistKeysToRedis": false,"PersistKeysToRedisUrl": "127.0.0.1:6379,allowAdmin=true,defaultDatabase=1"},-"Rabbit": {//Enable RabbitMq"RabbitEnabled": false,@@ -140,59 +133,55 @@//must be unique for each instance"RabbitCacheReceiveEndpoint": "grandnode"},+ "UrlRewrite": {+ //Load url rewrite rules from external file AppData/UrlRewrite.xml+ "UseUrlRewrite": false,+ "UrlRewriteHttpsOptions": false,+ "UrlRewriteHttpsOptionsStatusCode": 303,+ "UrlRewriteHttpsOptionsPort": 443,+ "UrlRedirectToHttpsPermanent": false+ },"Azure": {//Azure BLOB storage.//Specify your connection string, container name, end point for BLOB storage here"AzureBlobStorageConnectionString": "","AzureBlobStorageContainerName": "","AzureBlobStorageEndPoint": "",-//DataProtection - Azure Key Vault - you can use only one of method PersistKeysToAzureKeyVault or PersistKeysToAzureBlobStorage- "PersistKeysAzureBlobStorageConnectionString": "", //required+ "PersistKeysAzureBlobStorageConnectionString": "",+ //required"PersistKeysToAzureKeyVault": false,"PersistKeysToAzureBlobStorage": false,- "DataProtectionContainerName": "", //required- "DataProtectionBlobName": "keys.xml", //required- "KeyIdentifier": "" //required when use PersistKeysToAzureKeyVault-+ "DataProtectionContainerName": "",+ //required+ "DataProtectionBlobName": "keys.xml",+ //required+ "KeyIdentifier": "",+ //required when use PersistKeysToAzureKeyVault++ //Azure App Configuration+ "AppConfiguration": "",+ "AppKeyPrefix": ""},"Amazon": {-//Amazon Blob storage//<!--Available Region System Names can be found here http://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region -->"AmazonAwsAccessKeyId": "","AmazonAwsSecretAccessKey": "","AmazonBucketName": "","AmazonRegion": "",- "AmazonDistributionDomainName": "" //Domain name for cloudfront distribution-+ "AmazonDistributionDomainName": ""+ //Domain name for cloudfront distribution},- //access to the api to web controllers- "FrontendAPI": {- "Enabled": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- "RefreshTokenExpiryInMinutes": 1440- },- //api for admin- "BackendAPI": {- "Enabled": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- //generate system model- "SystemModel": true+ "FacebookSettings": {+ //Facebook-assigned App ID+ "AppId": "",+ //Facebook-assigned app secret+ "AppSecret": ""+ },+ "GoogleSettings": {+ "ClientId": "",+ "ClientSecret": ""},"Logging": {"LogLevel": {@@ -201,6 +190,15 @@}},"ApplicationInsights": {- "ConnectionString": ""+ "ConnectionString": "",+ "TrackDependencyMongoDb": false+ },+ //https://github.com/microsoft/ApplicationInsights-Profiler-AspNetCore/blob/main/Configurations.md+ "ServiceProfiler": {+ "IsDisabled": true,+ "Duration": "00:00:30",+ "InitialDelay": "00:00:03",+ "ProvideAnonymousTelemetry": true,+ "IsSkipCompatibilityTest": false}-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Admin/Controllers/LoginController.cs b/src/Web/Grand.Web.Admin/Controllers/LoginController.csindex c0011de37..c7e5c68f8 100644--- a/src/Web/Grand.Web.Admin/Controllers/LoginController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/LoginController.cs@@ -104,7 +104,7 @@ public class LoginController : BaseController//raise eventawait _mediator.Publish(new CustomerLoggedInEvent(customer));- return RedirectToRoute("AdminIndex", new RouteValueDictionary());+ return RedirectToRoute("AdminIndex");}public async Task<IActionResult> TwoFactorAuthorization(diff --git a/src/Web/Grand.Web.Admin/Grand.Web.Admin.csproj b/src/Web/Grand.Web.Admin/Grand.Web.Admin.csprojindex 6b6aaefe8..897a99644 100644--- a/src/Web/Grand.Web.Admin/Grand.Web.Admin.csproj+++ b/src/Web/Grand.Web.Admin/Grand.Web.Admin.csproj@@ -2,12 +2,13 @@<Import Project="..\..\Build\Grand.Common.props" /><PropertyGroup><AddRazorSupportForMvc>true</AddRazorSupportForMvc>- <ServerGarbageCollection>false</ServerGarbageCollection>- <EnableDefaultContentItems>false</EnableDefaultContentItems>+ <ServerGarbageCollection>true</ServerGarbageCollection>+ <GarbageCollectionAdaptationMode>1</GarbageCollectionAdaptationMode>+ <EnableDefaultContentItems>false</EnableDefaultContentItems><UseAppHost>false</UseAppHost><!--Set GenerateRuntimeConfigurationFiles as true when Admin panel is supposed to works independent--><GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>- </PropertyGroup>+ </PropertyGroup><ItemGroup><Content Include="Areas\**" CopyToPublishDirectory="Never" /><Content Include="wwwroot\**" CopyToPublishDirectory="PreserveNewest" />@@ -18,6 +19,7 @@<PackageReference Include="elFinder.Net.Drivers.FileSystem" /></ItemGroup><ItemGroup>+ <ProjectReference Include="..\..\Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj" /><ProjectReference Include="..\..\Business\Grand.Business.Core\Grand.Business.Core.csproj" /><ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj" /><ProjectReference Include="..\..\Core\Grand.Infrastructure\Grand.Infrastructure.csproj" />diff --git a/src/Web/Grand.Web.Admin/Program.cs b/src/Web/Grand.Web.Admin/Program.csindex decff92c7..e980ce09b 100644--- a/src/Web/Grand.Web.Admin/Program.cs+++ b/src/Web/Grand.Web.Admin/Program.cs@@ -5,6 +5,8 @@ using Microsoft.Extensions.Hosting;var builder = WebApplication.CreateBuilder(args);+builder.AddServiceDefaults();+builder.Host.UseDefaultServiceProvider((_, options) =>{options.ValidateScopes = false;diff --git a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.csdeleted file mode 100644index 1913628b6..000000000--- a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs+++ /dev/null@@ -1,39 +0,0 @@-using Grand.Data;-using Grand.Domain.Common;-using Grand.Infrastructure;-using Grand.Infrastructure.Caching;-using Grand.Infrastructure.Caching.Constants;-using Microsoft.AspNetCore.Http;--namespace Grand.Web.Common.Middleware;--public class DbVersionCheckMiddleware-{- private readonly RequestDelegate _next;-- public DbVersionCheckMiddleware(RequestDelegate next)- {- _next = next;- }-- public async Task Invoke(- HttpContext context,- ICacheBase cacheBase,- IRepository<GrandNodeVersion> repository)- {- if (context?.Request == null) return;-- var version = cacheBase.Get(CacheKey.GRAND_NODE_VERSION, () => repository.Table.FirstOrDefault());- if (version == null)- {- await context.Response.WriteAsync("The database does not exist.");- return;- }-- if (!version.DataBaseVersion.Equals(GrandVersion.SupportedDBVersion))- await context.Response.WriteAsync("The database version is not supported in this software version. " +- $"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}");- else- await _next(context);- }-}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.csindex 16fc3d7db..0b3de7625 100644--- a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs@@ -1,8 +1,11 @@using Grand.Data;+using Grand.Domain.Common;+using Grand.Infrastructure;+using Grand.Infrastructure.Caching;+using Grand.Infrastructure.Caching.Constants;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Http.Extensions;using Microsoft.Extensions.DependencyInjection;-using Microsoft.FeatureManagement;namespace Grand.Web.Common.Middleware;@@ -11,14 +14,17 @@ public class InstallUrlMiddleware#region Fieldsprivate readonly RequestDelegate _next;+ private readonly ICacheBase _cacheBase;+ private const string InstallUrl = "/install";#endregion#region Ctor- public InstallUrlMiddleware(RequestDelegate next)+ public InstallUrlMiddleware(RequestDelegate next, ICacheBase cacheBase){_next = next;+ _cacheBase = cacheBase;}#endregion@@ -32,31 +38,52 @@ public class InstallUrlMiddleware/// <returns>Task</returns>public async Task InvokeAsync(HttpContext context){- //whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())+ var databaseIsInstalled = DataSettingsManager.DatabaseIsInstalled();+ var version = GetDatabaseVersion(context, databaseIsInstalled);++ if (version == null){- var featureManager = context.RequestServices.GetRequiredService<IFeatureManager>();- var isInstallerModuleEnabled = await featureManager.IsEnabledAsync("Grand.Module.Installer");- if (!isInstallerModuleEnabled)+ if (!IsInstallUrl(context.Request)){- // Return a response indicating the installer module is not enabled- context.Response.StatusCode = StatusCodes.Status403Forbidden;- await context.Response.WriteAsync("The installation module is not enabled.");+ //redirect+ context.Response.Redirect(InstallUrl);return;}-- const string installUrl = "/install";- if (!context.Request.GetEncodedPathAndQuery().StartsWith(installUrl, StringComparison.OrdinalIgnoreCase))+ }+ else+ {+ if (!version.DataBaseVersion.Equals(GrandVersion.SupportedDBVersion))+ {+ await context.Response.WriteAsync("The database version is not supported in this software version. " ++ $"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}");+ return;+ }+ if (IsInstallUrl(context.Request)){//redirect- context.Response.Redirect(installUrl);+ context.Response.Redirect("/");return;}}- //or call the next middleware in the request pipeline+ //call the next middleware in the request pipelineawait _next(context);}+ private GrandNodeVersion? GetDatabaseVersion(HttpContext context, bool databaseIsInstalled)+ {+ return _cacheBase.Get(CacheKey.GRAND_NODE_VERSION, () =>+ {+ if (databaseIsInstalled)+ return context.RequestServices.GetRequiredService<IRepository<GrandNodeVersion>>().Table.FirstOrDefault();++ return null;+ }, int.MaxValue);+ }++ private bool IsInstallUrl(HttpRequest request)+ {+ return request.GetEncodedPathAndQuery().StartsWith(InstallUrl, StringComparison.OrdinalIgnoreCase);+ }#endregion-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.csindex ea200818b..06750a594 100644--- a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs@@ -10,7 +10,7 @@ public class WorkContextMiddlewareprivate readonly RequestDelegate _next;- private readonly List<string> skipRoutePattern = ["/scalar/{documentName}", "/openapi/{documentName}.json"];+ private readonly List<string> skipRoutePattern = ["/scalar/{documentName}", "/openapi/{documentName}.json", "install"];#endregiondiff --git a/src/Web/Grand.Web.Common/Startup/DbCheckStartup.cs b/src/Web/Grand.Web.Common/Startup/DbCheckStartup.csdeleted file mode 100644index d14c22645..000000000--- a/src/Web/Grand.Web.Common/Startup/DbCheckStartup.cs+++ /dev/null@@ -1,31 +0,0 @@-using Grand.Data;-using Grand.Infrastructure;-using Grand.Infrastructure.Configuration;-using Grand.Web.Common.Middleware;-using Microsoft.AspNetCore.Builder;-using Microsoft.AspNetCore.Hosting;-using Microsoft.Extensions.Configuration;-using Microsoft.Extensions.DependencyInjection;--namespace Grand.Web.Common.Startup;--public class DbCheckStartup : IStartupApplication-{- public int Priority => 0;- public bool BeforeConfigure => false;-- public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment)- {- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- var performanceConfig = application.Services.GetRequiredService<PerformanceConfig>();-- if (!performanceConfig.IgnoreDbVersionCheckMiddleware)- application.UseMiddleware<DbVersionCheckMiddleware>();- }-- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- }-}\ No newline at end of filediff --git a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json b/src/Web/Grand.Web.Vendor/App_Data/appsettings.jsonindex bc02b7fd1..898c13214 100644--- a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json+++ b/src/Web/Grand.Web.Vendor/App_Data/appsettings.json@@ -1,45 +1,45 @@{"Application": {-//Enable if you want to see the full error in production environment. It's ignored (always enabled) in development environment"DisplayFullErrorStack": true,-//Value of "Cache-Control" header value for static content"StaticFilesCacheControl": "public,max-age=31536000",-//Enable the session-based TempData provider"UseSessionStateTempDataProvider": false,-+ //A value indicating whether SEO friendly URLs with multiple languages are enabled+ "SeoFriendlyUrlsForLanguagesEnabled": false,+ "SeoFriendlyUrlsDefaultCode": "en",//Note: While use of custom response header encoding may be needed in some cases,//we discourage the use of non-ASCII encodings to avoid compatibility issues//with other HTTP clients."AllowNonAsciiCharInHeaders": false,-//Gets or sets the maximum allowed size of any request body in bytes//the default value is 30MB- "MaxRequestBodySize": null //max 2147483648- },+ "MaxRequestBodySize": null,+ //max 2147483648+ //Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore+ "EnableContextLoggingMiddleware": true+ },+ //only for advanced users, allow to set ConnectionString for MongoDb+ "ConnectionStrings": {+ "Mongodb": ""+ },"Database": {//This setting is required to use LiteDB database"UseLiteDb": false,//LiteDB database as a singleton service in the application"Singleton": true,//Init connection string - it's required only for the installation process!- "LiteDbConnectionString": "Filename=App_Data/database.db",- //only for advanced users, allow to set ConnectionString for MongoDb- "ConnectionString": "",- "DbProvider": 0+ "LiteDbConnectionString": "Filename=App_Data/database.db"},-"Security": {-//Use a reverse proxy server - more information you can find at: https://docs.microsoft.com/en-US/aspnet/core/host-and-deploy/linux-nginx"UseForwardedHeaders": false,-+ //In some cases, it might not be possible to add forwarded headers to the requests proxied to the app.+ "ForceUseHTTPS": false,//AllowedHosts, is used for host filtering to bind your app to specific hostnames"AllowedHosts": "*",-//This settings adds the following headers to all responses that pass//X-Content-Type-Options: nosniff//Strict-Transport-Security: max-age=31536000; includeSubDomains@@ -48,78 +48,72 @@//Referrer-Policy: strict-origin-when-cross-origin//Content-Security-Policy: object-src 'none'; form-action 'self'; frame-ancestors 'none'"UseDefaultSecurityHeaders": false,-//HTTP Strict Transport Security Protocol"UseHsts": false,-//When enabled, allow Razor files to be updated if they're edited.- "EnableRuntimeCompilation": true,-+ "EnableRuntimeCompilation": false,//We recommend all ASP.NET Core web apps call HTTPS Redirection Middleware to redirect all HTTP requests to HTTPS"UseHttpsRedirection": false,"HttpsRedirectionRedirect": 308,"HttpsRedirectionHttpsPort": 443,-//Key persistence location you can point to a directory on the local machine, or it can point to a folder on a network share.//if is null it will use the default directory path - ApplicationPath\App_Data\DataProtectionKeys- "KeyPersistenceLocation": null,-+ "KeyPersistenceLocation": "/App_Data/DataProtectionKeys",//Gets or sets a value indicating for cookie auth expires in hours - default 24 * 365 = 8760"CookieAuthExpires": 8760,-//Gets or sets a value for cookie prefix - any changes will log out all of the customers"CookiePrefix": ".Grand.",-//Gets or sets a value for cookie claim issuer - any changes will log out all of the customers"CookieClaimsIssuer": "grandnode",-//CookieSecurePolicy.Always always sets the Secure flag//Always setting the Secure flag is the most restrictive and most secure option.//This is the one you should be targeting if your production environment fully runs on HTTPS"CookieSecurePolicyAlways": false,-+ //Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks+ //Available values Unspecified, None, Lax, Strict+ "CookieSameSite": "Lax",+ "CookieSameSiteExternalAuth": "None",//Enabling this setting allows for verification of access to a specific controller and action in the admin panel using menu configuration."AuthorizeAdminMenu": false},-+ "Cache": {+ //Gets or sets a value indicating for default cache time in minutes"+ "DefaultCacheTimeMinutes": 60+ },"Extensions": {-//For developers - more info you can find at https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk///https://github.com/dotnet/roslyn/wiki/Roslyn-Overview"UseRoslynScripts": false,-- //Disable upload extensions plugins/themes+ //Disable upload extensions plugins"DisableUploadExtensions": false,-//A list of plugins to be ignored during start application - pattern"PluginSkipLoadingPattern": "",-//Enable if you want to clear /Plugins/bin directory on application startup"ClearPluginShadowDirectoryOnStartup": true,-//For develop you should enable if you want to copy plugin dll files to directory /Plugins/bin on application startup"PluginShadowCopy": true,+ //separator comma"InstalledPlugins": ""-- },- "Cache": {- //Gets or sets a value indicating for default cache time in minutes"- "DefaultCacheTimeMinutes": 60},"AccessControl": {/// A value indicating whether to ignore ACL rules"IgnoreAcl": false,-//A value indicating whether to ignore "limit per store" rules"IgnoreStoreLimitations": false},"Performance": {-//Indicates whether to compress response (gzip by default)//You may want to disable it, for example, If you have an active IIS Dynamic Compression Module configured at the server level- "UseResponseCompression": false+ "UseResponseCompression": false,+ //Indicates whether to ignore UsePoweredByMiddleware+ "IgnoreUsePoweredByMiddleware": false+ },+ "FeatureManagement": {+ "Grand.Module.Installer": false,+ "Grand.Module.Migration": false,+ "Grand.Module.ScheduledTasks": false,+ "Grand.Module.Api": false},-"Redis": {///Enable the Publish/Subscribe messaging with redis to manage memory cache on every server"RedisPubSubEnabled": false,@@ -128,7 +122,6 @@"PersistKeysToRedis": false,"PersistKeysToRedisUrl": "127.0.0.1:6379,allowAdmin=true,defaultDatabase=1"},-"Rabbit": {//Enable RabbitMq"RabbitEnabled": false,@@ -140,59 +133,55 @@//must be unique for each instance"RabbitCacheReceiveEndpoint": "grandnode"},+ "UrlRewrite": {+ //Load url rewrite rules from external file AppData/UrlRewrite.xml+ "UseUrlRewrite": false,+ "UrlRewriteHttpsOptions": false,+ "UrlRewriteHttpsOptionsStatusCode": 303,+ "UrlRewriteHttpsOptionsPort": 443,+ "UrlRedirectToHttpsPermanent": false+ },"Azure": {//Azure BLOB storage.//Specify your connection string, container name, end point for BLOB storage here"AzureBlobStorageConnectionString": "","AzureBlobStorageContainerName": "","AzureBlobStorageEndPoint": "",-//DataProtection - Azure Key Vault - you can use only one of method PersistKeysToAzureKeyVault or PersistKeysToAzureBlobStorage- "PersistKeysAzureBlobStorageConnectionString": "", //required+ "PersistKeysAzureBlobStorageConnectionString": "",+ //required"PersistKeysToAzureKeyVault": false,"PersistKeysToAzureBlobStorage": false,- "DataProtectionContainerName": "", //required- "DataProtectionBlobName": "keys.xml", //required- "KeyIdentifier": "" //required when use PersistKeysToAzureKeyVault-+ "DataProtectionContainerName": "",+ //required+ "DataProtectionBlobName": "keys.xml",+ //required+ "KeyIdentifier": "",+ //required when use PersistKeysToAzureKeyVault++ //Azure App Configuration+ "AppConfiguration": "",+ "AppKeyPrefix": ""},"Amazon": {-//Amazon Blob storage//<!--Available Region System Names can be found here http://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region -->"AmazonAwsAccessKeyId": "","AmazonAwsSecretAccessKey": "","AmazonBucketName": "","AmazonRegion": "",- "AmazonDistributionDomainName": "" //Domain name for cloudfront distribution-+ "AmazonDistributionDomainName": ""+ //Domain name for cloudfront distribution},- //access to the api to web controllers- "FrontendAPI": {- "Enabled": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- "RefreshTokenExpiryInMinutes": 1440- },- //api for admin- "BackendAPI": {- "Enabled": false,- "SecretKey": "your private secret key", //at least 16 characters- "ValidateIssuer": false,- "ValidIssuer": "",- "ValidateAudience": false,- "ValidAudience": "",- "ValidateLifetime": true,- "ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440,- //generate system model- "SystemModel": true+ "FacebookSettings": {+ //Facebook-assigned App ID+ "AppId": "",+ //Facebook-assigned app secret+ "AppSecret": ""+ },+ "GoogleSettings": {+ "ClientId": "",+ "ClientSecret": ""},"Logging": {"LogLevel": {@@ -201,6 +190,15 @@}},"ApplicationInsights": {- "ConnectionString": ""+ "ConnectionString": "",+ "TrackDependencyMongoDb": false+ },+ //https://github.com/microsoft/ApplicationInsights-Profiler-AspNetCore/blob/main/Configurations.md+ "ServiceProfiler": {+ "IsDisabled": true,+ "Duration": "00:00:30",+ "InitialDelay": "00:00:03",+ "ProvideAnonymousTelemetry": true,+ "IsSkipCompatibilityTest": false}-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Vendor/Grand.Web.Vendor.csproj b/src/Web/Grand.Web.Vendor/Grand.Web.Vendor.csprojindex 9f2f7baaa..bd44fedb6 100644--- a/src/Web/Grand.Web.Vendor/Grand.Web.Vendor.csproj+++ b/src/Web/Grand.Web.Vendor/Grand.Web.Vendor.csproj@@ -4,9 +4,9 @@<AddRazorSupportForMvc>true</AddRazorSupportForMvc><ServerGarbageCollection>false</ServerGarbageCollection><EnableDefaultContentItems>false</EnableDefaultContentItems>- <UseAppHost>false</UseAppHost>+ <UseAppHost>false</UseAppHost><!--Set GenerateRuntimeConfigurationFiles as true when Vendor panel is supposed to works independent-->- <GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles>+ <GenerateRuntimeConfigurationFiles>false</GenerateRuntimeConfigurationFiles></PropertyGroup><ItemGroup><Content Include="Areas\**" CopyToPublishDirectory="Never" />diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.jsonindex c46438c4b..8beaa9493 100644--- a/src/Web/Grand.Web/App_Data/appsettings.json+++ b/src/Web/Grand.Web/App_Data/appsettings.json@@ -21,16 +21,17 @@//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore"EnableContextLoggingMiddleware": true},+ //only for advanced users, allow to set ConnectionString for MongoDb+ "ConnectionStrings": {+ "Mongodb": ""+ },"Database": {//This setting is required to use LiteDB database"UseLiteDb": false,//LiteDB database as a singleton service in the application"Singleton": true,//Init connection string - it's required only for the installation process!- "LiteDbConnectionString": "Filename=App_Data/database.db",- //only for advanced users, allow to set ConnectionString for MongoDb- "ConnectionString": "",- "DbProvider": 0+ "LiteDbConnectionString": "Filename=App_Data/database.db"},"Security": {//Use a reverse proxy server - more information you can find at: https://docs.microsoft.com/en-US/aspnet/core/host-and-deploy/linux-nginx@@ -104,8 +105,6 @@//Indicates whether to compress response (gzip by default)//You may want to disable it, for example, If you have an active IIS Dynamic Compression Module configured at the server level"UseResponseCompression": false,- //Indicates whether to ignore DbVersionCheckMiddleware- "IgnoreDbVersionCheckMiddleware": false,//Indicates whether to ignore UsePoweredByMiddleware"IgnoreUsePoweredByMiddleware": false},diff --git a/src/Web/Grand.Web/Grand.Web.csproj b/src/Web/Grand.Web/Grand.Web.csprojindex e14340768..2dc8e420b 100644--- a/src/Web/Grand.Web/Grand.Web.csproj+++ b/src/Web/Grand.Web/Grand.Web.csproj@@ -16,6 +16,7 @@<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS></PropertyGroup><ItemGroup>+ <ProjectReference Include="..\..\Aspire\Aspire.ServiceDefaults\Aspire.ServiceDefaults.csproj" /><ProjectReference Include="..\..\Business\Grand.Business.Core\Grand.Business.Core.csproj" /><ProjectReference Include="..\..\Core\Grand.Domain\Grand.Domain.csproj" /><ProjectReference Include="..\..\Core\Grand.Infrastructure\Grand.Infrastructure.csproj" />diff --git a/src/Web/Grand.Web/Program.cs b/src/Web/Grand.Web/Program.csindex d0bcaada7..fcce538dd 100644--- a/src/Web/Grand.Web/Program.cs+++ b/src/Web/Grand.Web/Program.cs@@ -1,4 +1,4 @@-using Grand.Web.Common.Extensions;+using Grand.Web.Common.Extensions;using Grand.Web.Common.Startup;using Microsoft.AspNetCore.Builder;using Microsoft.Extensions.Hosting;@@ -6,6 +6,8 @@ using StartupBase = Grand.Infrastructure.StartupBase;var builder = WebApplication.CreateBuilder(args);+builder.AddServiceDefaults();+builder.Host.UseDefaultServiceProvider((_, options) =>{options.ValidateScopes = false;