net6conversion (#642)
* Converting to net6 startup and integration test formats * Update to minimal api and using pagetitle * Adjust functional test fixtures Update ApiEndpoints package version * Finish migration to minimal api startup
This commit is contained in:
@@ -65,6 +65,16 @@ dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_
|
|||||||
dotnet_naming_symbols.constant_fields.applicable_kinds = field
|
dotnet_naming_symbols.constant_fields.applicable_kinds = field
|
||||||
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
|
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
|
||||||
dotnet_naming_symbols.constant_fields.required_modifiers = const
|
dotnet_naming_symbols.constant_fields.required_modifiers = const
|
||||||
|
|
||||||
|
# Instance fields are camelCase and start with _
|
||||||
|
dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion
|
||||||
|
dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields
|
||||||
|
dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style
|
||||||
|
|
||||||
|
dotnet_naming_symbols.instance_fields.applicable_kinds = field
|
||||||
|
|
||||||
|
dotnet_naming_style.instance_field_style.capitalization = camel_case
|
||||||
|
dotnet_naming_style.instance_field_style.required_prefix = _
|
||||||
###############################
|
###############################
|
||||||
# C# Coding Conventions #
|
# C# Coding Conventions #
|
||||||
###############################
|
###############################
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
# Visual Studio Version 16
|
# Visual Studio Version 17
|
||||||
VisualStudioVersion = 16.0.29102.190
|
VisualStudioVersion = 17.0.31903.59
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{419A6ACE-0419-4315-A6FB-B0E63D39432E}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{419A6ACE-0419-4315-A6FB-B0E63D39432E}"
|
||||||
EndProject
|
EndProject
|
||||||
@@ -23,6 +23,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FunctionalTests", "tests\Fu
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0BD72BEA-EF42-4B72-8B69-12A39EC76FBA}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0BD72BEA-EF42-4B72-8B69-12A39EC76FBA}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
|
.editorconfig = .editorconfig
|
||||||
docker-compose.override.yml = docker-compose.override.yml
|
docker-compose.override.yml = docker-compose.override.yml
|
||||||
docker-compose.yml = docker-compose.yml
|
docker-compose.yml = docker-compose.yml
|
||||||
.github\workflows\dotnetcore.yml = .github\workflows\dotnetcore.yml
|
.github\workflows\dotnetcore.yml = .github\workflows\dotnetcore.yml
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
@inherits BlazorAdmin.Helpers.BlazorComponent
|
@inherits BlazorAdmin.Helpers.BlazorComponent
|
||||||
@namespace BlazorAdmin.Pages.CatalogItemPage
|
@namespace BlazorAdmin.Pages.CatalogItemPage
|
||||||
|
|
||||||
|
<PageTitle>eShopOnWeb Admin: Manage Product Catalog</PageTitle>
|
||||||
|
|
||||||
<h1>Manage Product Catalog</h1>
|
<h1>Manage Product Catalog</h1>
|
||||||
|
|
||||||
@if (catalogItems == null)
|
@if (catalogItems == null)
|
||||||
|
|||||||
@@ -1,24 +1,21 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using BlazorAdmin;
|
||||||
using BlazorAdmin.Services;
|
using BlazorAdmin.Services;
|
||||||
using Blazored.LocalStorage;
|
using Blazored.LocalStorage;
|
||||||
using BlazorShared;
|
using BlazorShared;
|
||||||
using BlazorShared.Models;
|
using BlazorShared.Models;
|
||||||
using Microsoft.AspNetCore.Components.Authorization;
|
using Microsoft.AspNetCore.Components.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Components.Web;
|
||||||
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace BlazorAdmin;
|
|
||||||
|
|
||||||
public class Program
|
|
||||||
{
|
|
||||||
public static async Task Main(string[] args)
|
|
||||||
{
|
|
||||||
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
var builder = WebAssemblyHostBuilder.CreateDefault(args);
|
||||||
builder.RootComponents.Add<App>("#admin");
|
builder.RootComponents.Add<App>("#admin");
|
||||||
|
builder.RootComponents.Add<HeadOutlet>("head::after");
|
||||||
|
|
||||||
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
||||||
builder.Services.Configure<BaseUrlConfiguration>(configSection);
|
builder.Services.Configure<BaseUrlConfiguration>(configSection);
|
||||||
@@ -41,9 +38,8 @@ public class Program
|
|||||||
await ClearLocalStorageCache(builder.Services);
|
await ClearLocalStorageCache(builder.Services);
|
||||||
|
|
||||||
await builder.Build().RunAsync();
|
await builder.Build().RunAsync();
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task ClearLocalStorageCache(IServiceCollection services)
|
static async Task ClearLocalStorageCache(IServiceCollection services)
|
||||||
{
|
{
|
||||||
var sp = services.BuildServiceProvider();
|
var sp = services.BuildServiceProvider();
|
||||||
var localStorageService = sp.GetRequiredService<ILocalStorageService>();
|
var localStorageService = sp.GetRequiredService<ILocalStorageService>();
|
||||||
@@ -51,4 +47,3 @@ public class Program
|
|||||||
await localStorageService.RemoveItemAsync(typeof(CatalogBrand).Name);
|
await localStorageService.RemoveItemAsync(typeof(CatalogBrand).Name);
|
||||||
await localStorageService.RemoveItemAsync(typeof(CatalogType).Name);
|
await localStorageService.RemoveItemAsync(typeof(CatalogType).Name);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ namespace Microsoft.eShopWeb.Infrastructure.Data;
|
|||||||
public class CatalogContextSeed
|
public class CatalogContextSeed
|
||||||
{
|
{
|
||||||
public static async Task SeedAsync(CatalogContext catalogContext,
|
public static async Task SeedAsync(CatalogContext catalogContext,
|
||||||
ILoggerFactory loggerFactory, int retry = 0)
|
ILogger logger,
|
||||||
|
int retry = 0)
|
||||||
{
|
{
|
||||||
var retryForAvailability = retry;
|
var retryForAvailability = retry;
|
||||||
try
|
try
|
||||||
@@ -49,9 +50,9 @@ public class CatalogContextSeed
|
|||||||
if (retryForAvailability >= 10) throw;
|
if (retryForAvailability >= 10) throw;
|
||||||
|
|
||||||
retryForAvailability++;
|
retryForAvailability++;
|
||||||
var log = loggerFactory.CreateLogger<CatalogContextSeed>();
|
|
||||||
log.LogError(ex.Message);
|
logger.LogError(ex.Message);
|
||||||
await SeedAsync(catalogContext, loggerFactory, retryForAvailability);
|
await SeedAsync(catalogContext, logger, retryForAvailability);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.AuthEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.AuthEndpoints;
|
||||||
|
|
||||||
public class Authenticate : BaseAsyncEndpoint
|
public class Authenticate : EndpointBaseAsync
|
||||||
.WithRequest<AuthenticateRequest>
|
.WithRequest<AuthenticateRequest>
|
||||||
.WithResponse<AuthenticateResponse>
|
.WithActionResult<AuthenticateResponse>
|
||||||
{
|
{
|
||||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||||
private readonly ITokenClaimsService _tokenClaimsService;
|
private readonly ITokenClaimsService _tokenClaimsService;
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogBrandEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogBrandEndpoints;
|
||||||
|
|
||||||
public class List : BaseAsyncEndpoint
|
public class List : EndpointBaseAsync
|
||||||
.WithoutRequest
|
.WithoutRequest
|
||||||
.WithResponse<ListCatalogBrandsResponse>
|
.WithActionResult<ListCatalogBrandsResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogBrand> _catalogBrandRepository;
|
private readonly IRepository<CatalogBrand> _catalogBrandRepository;
|
||||||
private readonly IMapper _mapper;
|
private readonly IMapper _mapper;
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
||||||
|
|
||||||
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
||||||
public class Create : BaseAsyncEndpoint
|
public class Create : EndpointBaseAsync
|
||||||
.WithRequest<CreateCatalogItemRequest>
|
.WithRequest<CreateCatalogItemRequest>
|
||||||
.WithResponse<CreateCatalogItemResponse>
|
.WithActionResult<CreateCatalogItemResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogItem> _itemRepository;
|
private readonly IRepository<CatalogItem> _itemRepository;
|
||||||
private readonly IUriComposer _uriComposer;
|
private readonly IUriComposer _uriComposer;
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
||||||
|
|
||||||
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
||||||
public class Delete : BaseAsyncEndpoint
|
public class Delete : EndpointBaseAsync
|
||||||
.WithRequest<DeleteCatalogItemRequest>
|
.WithRequest<DeleteCatalogItemRequest>
|
||||||
.WithResponse<DeleteCatalogItemResponse>
|
.WithActionResult<DeleteCatalogItemResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogItem> _itemRepository;
|
private readonly IRepository<CatalogItem> _itemRepository;
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
||||||
|
|
||||||
public class GetById : BaseAsyncEndpoint
|
public class GetById : EndpointBaseAsync
|
||||||
.WithRequest<GetByIdCatalogItemRequest>
|
.WithRequest<GetByIdCatalogItemRequest>
|
||||||
.WithResponse<GetByIdCatalogItemResponse>
|
.WithActionResult<GetByIdCatalogItemResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogItem> _itemRepository;
|
private readonly IRepository<CatalogItem> _itemRepository;
|
||||||
private readonly IUriComposer _uriComposer;
|
private readonly IUriComposer _uriComposer;
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
||||||
|
|
||||||
public class ListPaged : BaseAsyncEndpoint
|
public class ListPaged : EndpointBaseAsync
|
||||||
.WithRequest<ListPagedCatalogItemRequest>
|
.WithRequest<ListPagedCatalogItemRequest>
|
||||||
.WithResponse<ListPagedCatalogItemResponse>
|
.WithActionResult<ListPagedCatalogItemResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogItem> _itemRepository;
|
private readonly IRepository<CatalogItem> _itemRepository;
|
||||||
private readonly IUriComposer _uriComposer;
|
private readonly IUriComposer _uriComposer;
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
|
||||||
|
|
||||||
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
|
||||||
public class Update : BaseAsyncEndpoint
|
public class Update : EndpointBaseAsync
|
||||||
.WithRequest<UpdateCatalogItemRequest>
|
.WithRequest<UpdateCatalogItemRequest>
|
||||||
.WithResponse<UpdateCatalogItemResponse>
|
.WithActionResult<UpdateCatalogItemResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogItem> _itemRepository;
|
private readonly IRepository<CatalogItem> _itemRepository;
|
||||||
private readonly IUriComposer _uriComposer;
|
private readonly IUriComposer _uriComposer;
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ using Swashbuckle.AspNetCore.Annotations;
|
|||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.CatalogTypeEndpoints;
|
namespace Microsoft.eShopWeb.PublicApi.CatalogTypeEndpoints;
|
||||||
|
|
||||||
public class List : BaseAsyncEndpoint
|
public class List : EndpointBaseAsync
|
||||||
.WithoutRequest
|
.WithoutRequest
|
||||||
.WithResponse<ListCatalogTypesResponse>
|
.WithActionResult<ListCatalogTypesResponse>
|
||||||
{
|
{
|
||||||
private readonly IRepository<CatalogType> _catalogTypeRepository;
|
private readonly IRepository<CatalogType> _catalogTypeRepository;
|
||||||
private readonly IMapper _mapper;
|
private readonly IMapper _mapper;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ using BlazorShared.Models;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Exceptions;
|
using Microsoft.eShopWeb.ApplicationCore.Exceptions;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi.MiddleWares;
|
namespace Microsoft.eShopWeb.PublicApi.Middleware;
|
||||||
|
|
||||||
public class ExceptionMiddleware
|
public class ExceptionMiddleware
|
||||||
{
|
{
|
||||||
@@ -1,50 +1,186 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using BlazorShared;
|
||||||
|
using BlazorShared.Models;
|
||||||
|
using MediatR;
|
||||||
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.eShopWeb;
|
||||||
|
using Microsoft.eShopWeb.ApplicationCore.Constants;
|
||||||
|
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
|
||||||
|
using Microsoft.eShopWeb.ApplicationCore.Services;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
using Microsoft.eShopWeb.Infrastructure.Data;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
using Microsoft.eShopWeb.Infrastructure.Identity;
|
||||||
|
using Microsoft.eShopWeb.Infrastructure.Logging;
|
||||||
|
using Microsoft.eShopWeb.PublicApi;
|
||||||
|
using Microsoft.eShopWeb.PublicApi.Middleware;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Microsoft.OpenApi.Models;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi;
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
public class Program
|
builder.Logging.AddConsole();
|
||||||
{
|
|
||||||
public static async Task Main(string[] args)
|
|
||||||
{
|
|
||||||
var host = CreateHostBuilder(args)
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
using (var scope = host.Services.CreateScope())
|
// use real database
|
||||||
|
// Requires LocalDB which can be installed with SQL Server Express 2016
|
||||||
|
// https://www.microsoft.com/en-us/download/details.aspx?id=54284
|
||||||
|
builder.Services.AddDbContext<CatalogContext>(c =>
|
||||||
|
c.UseSqlServer(builder.Configuration.GetConnectionString("CatalogConnection")));
|
||||||
|
|
||||||
|
// Add Identity DbContext
|
||||||
|
builder.Services.AddDbContext<AppIdentityDbContext>(options =>
|
||||||
|
options.UseSqlServer(builder.Configuration.GetConnectionString("IdentityConnection")));
|
||||||
|
|
||||||
|
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
|
||||||
|
.AddEntityFrameworkStores<AppIdentityDbContext>()
|
||||||
|
.AddDefaultTokenProviders();
|
||||||
|
|
||||||
|
builder.Services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
|
||||||
|
builder.Services.AddScoped(typeof(IReadRepository<>), typeof(EfRepository<>));
|
||||||
|
builder.Services.Configure<CatalogSettings>(builder.Configuration);
|
||||||
|
builder.Services.AddSingleton<IUriComposer>(new UriComposer(builder.Configuration.Get<CatalogSettings>()));
|
||||||
|
builder.Services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
|
||||||
|
builder.Services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
|
||||||
|
|
||||||
|
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
||||||
|
builder.Services.Configure<BaseUrlConfiguration>(configSection);
|
||||||
|
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
|
||||||
|
|
||||||
|
builder.Services.AddMemoryCache();
|
||||||
|
|
||||||
|
var key = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY);
|
||||||
|
builder.Services.AddAuthentication(config =>
|
||||||
{
|
{
|
||||||
var services = scope.ServiceProvider;
|
config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
|
})
|
||||||
|
.AddJwtBearer(config =>
|
||||||
|
{
|
||||||
|
config.RequireHttpsMetadata = false;
|
||||||
|
config.SaveToken = true;
|
||||||
|
config.TokenValidationParameters = new TokenValidationParameters
|
||||||
|
{
|
||||||
|
ValidateIssuerSigningKey = true,
|
||||||
|
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||||||
|
ValidateIssuer = false,
|
||||||
|
ValidateAudience = false
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const string CORS_POLICY = "CorsPolicy";
|
||||||
|
builder.Services.AddCors(options =>
|
||||||
|
{
|
||||||
|
options.AddPolicy(name: CORS_POLICY,
|
||||||
|
builder =>
|
||||||
|
{
|
||||||
|
builder.WithOrigins(baseUrlConfig.WebBase.Replace("host.docker.internal", "localhost").TrimEnd('/'));
|
||||||
|
builder.AllowAnyMethod();
|
||||||
|
builder.AllowAnyHeader();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
|
builder.Services.AddMediatR(typeof(CatalogItem).Assembly);
|
||||||
|
builder.Services.AddAutoMapper(typeof(MappingProfile).Assembly);
|
||||||
|
|
||||||
|
builder.Services.AddSwaggerGen(c =>
|
||||||
|
{
|
||||||
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
||||||
|
c.EnableAnnotations();
|
||||||
|
c.SchemaFilter<CustomSchemaFilters>();
|
||||||
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n
|
||||||
|
Enter 'Bearer' [space] and then your token in the text input below.
|
||||||
|
\r\n\r\nExample: 'Bearer 12345abcdef'",
|
||||||
|
Name = "Authorization",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
Type = SecuritySchemeType.ApiKey,
|
||||||
|
Scheme = "Bearer"
|
||||||
|
});
|
||||||
|
|
||||||
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||||
|
{
|
||||||
|
{
|
||||||
|
new OpenApiSecurityScheme
|
||||||
|
{
|
||||||
|
Reference = new OpenApiReference
|
||||||
|
{
|
||||||
|
Type = ReferenceType.SecurityScheme,
|
||||||
|
Id = "Bearer"
|
||||||
|
},
|
||||||
|
Scheme = "oauth2",
|
||||||
|
Name = "Bearer",
|
||||||
|
In = ParameterLocation.Header,
|
||||||
|
|
||||||
|
},
|
||||||
|
new List<string>()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.Logger.LogInformation("PublicApi App created...");
|
||||||
|
|
||||||
|
if (app.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
app.UseDeveloperExceptionPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseMiddleware<ExceptionMiddleware>();
|
||||||
|
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
|
||||||
|
app.UseRouting();
|
||||||
|
|
||||||
|
app.UseCors(CORS_POLICY);
|
||||||
|
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
// Enable middleware to serve generated Swagger as a JSON endpoint.
|
||||||
|
app.UseSwagger();
|
||||||
|
|
||||||
|
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
|
||||||
|
// specifying the Swagger JSON endpoint.
|
||||||
|
app.UseSwaggerUI(c =>
|
||||||
|
{
|
||||||
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
|
||||||
|
});
|
||||||
|
|
||||||
|
app.UseEndpoints(endpoints =>
|
||||||
|
{
|
||||||
|
endpoints.MapControllers();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.Logger.LogInformation("Seeding Database...");
|
||||||
|
|
||||||
|
using (var scope = app.Services.CreateScope())
|
||||||
|
{
|
||||||
|
var scopedProvider = scope.ServiceProvider;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var catalogContext = services.GetRequiredService<CatalogContext>();
|
var catalogContext = scopedProvider.GetRequiredService<CatalogContext>();
|
||||||
await CatalogContextSeed.SeedAsync(catalogContext, loggerFactory);
|
await CatalogContextSeed.SeedAsync(catalogContext, app.Logger);
|
||||||
|
|
||||||
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
|
var userManager = scopedProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||||
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
|
var roleManager = scopedProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||||
await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager);
|
await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
var logger = loggerFactory.CreateLogger<Program>();
|
app.Logger.LogError(ex, "An error occurred seeding the DB.");
|
||||||
logger.LogError(ex, "An error occurred seeding the DB.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host.Run();
|
app.Logger.LogInformation("LAUNCHING PublicApi");
|
||||||
}
|
app.Run();
|
||||||
|
|
||||||
|
|
||||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
|
||||||
Host.CreateDefaultBuilder(args)
|
|
||||||
.ConfigureWebHostDefaults(webBuilder =>
|
|
||||||
{
|
|
||||||
webBuilder.UseStartup<Startup>();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Ardalis.ApiEndpoints" Version="3.1.0" />
|
<PackageReference Include="Ardalis.ApiEndpoints" Version="4.0.0-pre1" />
|
||||||
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
|
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
|
||||||
<PackageReference Include="MediatR" Version="9.0.0" />
|
<PackageReference Include="MediatR" Version="9.0.0" />
|
||||||
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
|
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="9.0.0" />
|
||||||
|
|||||||
@@ -1,208 +0,0 @@
|
|||||||
using System.Collections.Generic;
|
|
||||||
using System.Text;
|
|
||||||
using AutoMapper;
|
|
||||||
using BlazorShared;
|
|
||||||
using MediatR;
|
|
||||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
||||||
using Microsoft.AspNetCore.Builder;
|
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Identity;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Constants;
|
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Entities;
|
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
|
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Services;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Logging;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Services;
|
|
||||||
using Microsoft.eShopWeb.PublicApi.MiddleWares;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
|
||||||
using Microsoft.OpenApi.Models;
|
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.PublicApi;
|
|
||||||
|
|
||||||
public class Startup
|
|
||||||
{
|
|
||||||
private const string CORS_POLICY = "CorsPolicy";
|
|
||||||
|
|
||||||
public Startup(IConfiguration configuration)
|
|
||||||
{
|
|
||||||
Configuration = configuration;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IConfiguration Configuration { get; }
|
|
||||||
|
|
||||||
public void ConfigureDevelopmentServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// use in-memory database
|
|
||||||
ConfigureInMemoryDatabases(services);
|
|
||||||
|
|
||||||
// use real database
|
|
||||||
//ConfigureProductionServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureDockerServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
ConfigureDevelopmentServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ConfigureInMemoryDatabases(IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddDbContext<CatalogContext>(c =>
|
|
||||||
c.UseInMemoryDatabase("Catalog"));
|
|
||||||
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
|
||||||
options.UseInMemoryDatabase("Identity"));
|
|
||||||
|
|
||||||
ConfigureServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureProductionServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// use real database
|
|
||||||
// Requires LocalDB which can be installed with SQL Server Express 2016
|
|
||||||
// https://www.microsoft.com/en-us/download/details.aspx?id=54284
|
|
||||||
services.AddDbContext<CatalogContext>(c =>
|
|
||||||
c.UseSqlServer(Configuration.GetConnectionString("CatalogConnection")));
|
|
||||||
|
|
||||||
// Add Identity DbContext
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
|
||||||
options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));
|
|
||||||
|
|
||||||
ConfigureServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureTestingServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
ConfigureInMemoryDatabases(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to add services to the container.
|
|
||||||
public void ConfigureServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddIdentity<ApplicationUser, IdentityRole>()
|
|
||||||
.AddEntityFrameworkStores<AppIdentityDbContext>()
|
|
||||||
.AddDefaultTokenProviders();
|
|
||||||
|
|
||||||
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
|
|
||||||
services.AddScoped(typeof(IReadRepository<>), typeof(EfRepository<>));
|
|
||||||
services.Configure<CatalogSettings>(Configuration);
|
|
||||||
services.AddSingleton<IUriComposer>(new UriComposer(Configuration.Get<CatalogSettings>()));
|
|
||||||
services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
|
|
||||||
services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
|
|
||||||
|
|
||||||
var configSection = Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
|
||||||
services.Configure<BaseUrlConfiguration>(configSection);
|
|
||||||
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
|
|
||||||
|
|
||||||
services.AddMemoryCache();
|
|
||||||
|
|
||||||
var key = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY);
|
|
||||||
services.AddAuthentication(config =>
|
|
||||||
{
|
|
||||||
config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
||||||
})
|
|
||||||
.AddJwtBearer(config =>
|
|
||||||
{
|
|
||||||
config.RequireHttpsMetadata = false;
|
|
||||||
config.SaveToken = true;
|
|
||||||
config.TokenValidationParameters = new TokenValidationParameters
|
|
||||||
{
|
|
||||||
ValidateIssuerSigningKey = true,
|
|
||||||
IssuerSigningKey = new SymmetricSecurityKey(key),
|
|
||||||
ValidateIssuer = false,
|
|
||||||
ValidateAudience = false
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddCors(options =>
|
|
||||||
{
|
|
||||||
options.AddPolicy(name: CORS_POLICY,
|
|
||||||
builder =>
|
|
||||||
{
|
|
||||||
builder.WithOrigins(baseUrlConfig.WebBase.Replace("host.docker.internal", "localhost").TrimEnd('/'));
|
|
||||||
builder.AllowAnyMethod();
|
|
||||||
builder.AllowAnyHeader();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddControllers();
|
|
||||||
services.AddMediatR(typeof(CatalogItem).Assembly);
|
|
||||||
|
|
||||||
services.AddAutoMapper(typeof(Startup).Assembly);
|
|
||||||
services.AddSwaggerGen(c =>
|
|
||||||
{
|
|
||||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
|
|
||||||
c.EnableAnnotations();
|
|
||||||
c.SchemaFilter<CustomSchemaFilters>();
|
|
||||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n
|
|
||||||
Enter 'Bearer' [space] and then your token in the text input below.
|
|
||||||
\r\n\r\nExample: 'Bearer 12345abcdef'",
|
|
||||||
Name = "Authorization",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
Type = SecuritySchemeType.ApiKey,
|
|
||||||
Scheme = "Bearer"
|
|
||||||
});
|
|
||||||
|
|
||||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
|
||||||
{
|
|
||||||
{
|
|
||||||
new OpenApiSecurityScheme
|
|
||||||
{
|
|
||||||
Reference = new OpenApiReference
|
|
||||||
{
|
|
||||||
Type = ReferenceType.SecurityScheme,
|
|
||||||
Id = "Bearer"
|
|
||||||
},
|
|
||||||
Scheme = "oauth2",
|
|
||||||
Name = "Bearer",
|
|
||||||
In = ParameterLocation.Header,
|
|
||||||
|
|
||||||
},
|
|
||||||
new List<string>()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|
||||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|
||||||
{
|
|
||||||
if (env.IsDevelopment())
|
|
||||||
{
|
|
||||||
app.UseDeveloperExceptionPage();
|
|
||||||
}
|
|
||||||
|
|
||||||
app.UseMiddleware<ExceptionMiddleware>();
|
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
|
||||||
|
|
||||||
app.UseRouting();
|
|
||||||
|
|
||||||
app.UseCors(CORS_POLICY);
|
|
||||||
|
|
||||||
app.UseAuthorization();
|
|
||||||
|
|
||||||
// Enable middleware to serve generated Swagger as a JSON endpoint.
|
|
||||||
app.UseSwagger();
|
|
||||||
|
|
||||||
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
|
|
||||||
// specifying the Swagger JSON endpoint.
|
|
||||||
app.UseSwaggerUI(c =>
|
|
||||||
{
|
|
||||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
|
|
||||||
});
|
|
||||||
|
|
||||||
app.UseEndpoints(endpoints =>
|
|
||||||
{
|
|
||||||
endpoints.MapControllers();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -53,7 +53,7 @@ public class LoginModel : PageModel
|
|||||||
public bool RememberMe { get; set; }
|
public bool RememberMe { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task OnGetAsync(string returnUrl = null)
|
public async Task OnGetAsync(string? returnUrl = null)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(ErrorMessage))
|
if (!string.IsNullOrEmpty(ErrorMessage))
|
||||||
{
|
{
|
||||||
@@ -70,7 +70,7 @@ public class LoginModel : PageModel
|
|||||||
ReturnUrl = returnUrl;
|
ReturnUrl = returnUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
|
public async Task<IActionResult> OnPostAsync(string? returnUrl = null)
|
||||||
{
|
{
|
||||||
returnUrl = returnUrl ?? Url.Content("~/");
|
returnUrl = returnUrl ?? Url.Content("~/");
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Threading.Tasks;
|
using Microsoft.eShopWeb.ApplicationCore.Entities.BasketAggregate;
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Entities.BasketAggregate;
|
|
||||||
using Microsoft.eShopWeb.Web.Pages.Basket;
|
using Microsoft.eShopWeb.Web.Pages.Basket;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.Web.Interfaces;
|
namespace Microsoft.eShopWeb.Web.Interfaces;
|
||||||
|
|||||||
@@ -1,49 +1,198 @@
|
|||||||
using System;
|
using System.Net.Mime;
|
||||||
using System.Threading.Tasks;
|
using Ardalis.ListStartupServices;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
using BlazorAdmin;
|
||||||
|
using BlazorAdmin.Services;
|
||||||
|
using Blazored.LocalStorage;
|
||||||
|
using BlazorShared;
|
||||||
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||||||
using Microsoft.AspNetCore.Identity;
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.eShopWeb;
|
||||||
|
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
using Microsoft.eShopWeb.Infrastructure.Data;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
using Microsoft.eShopWeb.Infrastructure.Identity;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.eShopWeb.Web;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.eShopWeb.Web.Configuration;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.eShopWeb.Web.HealthChecks;
|
||||||
|
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.Web;
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
public class Program
|
builder.Logging.AddConsole();
|
||||||
{
|
|
||||||
public static async Task Main(string[] args)
|
|
||||||
{
|
|
||||||
var host = CreateHostBuilder(args)
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
using (var scope = host.Services.CreateScope())
|
// use real database
|
||||||
|
// Requires LocalDB which can be installed with SQL Server Express 2016
|
||||||
|
// https://www.microsoft.com/en-us/download/details.aspx?id=54284
|
||||||
|
builder.Services.AddDbContext<CatalogContext>(c =>
|
||||||
|
c.UseSqlServer(builder.Configuration.GetConnectionString("CatalogConnection")));
|
||||||
|
|
||||||
|
// Add Identity DbContext
|
||||||
|
builder.Services.AddDbContext<AppIdentityDbContext>(options =>
|
||||||
|
options.UseSqlServer(builder.Configuration.GetConnectionString("IdentityConnection")));
|
||||||
|
|
||||||
|
builder.Services.AddCookieSettings();
|
||||||
|
|
||||||
|
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||||
|
.AddCookie(options =>
|
||||||
{
|
{
|
||||||
var services = scope.ServiceProvider;
|
options.Cookie.HttpOnly = true;
|
||||||
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
|
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||||
|
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
|
||||||
|
.AddDefaultUI()
|
||||||
|
.AddEntityFrameworkStores<AppIdentityDbContext>()
|
||||||
|
.AddDefaultTokenProviders();
|
||||||
|
|
||||||
|
builder.Services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
|
||||||
|
|
||||||
|
builder.Services.AddCoreServices(builder.Configuration);
|
||||||
|
builder.Services.AddWebServices(builder.Configuration);
|
||||||
|
|
||||||
|
// Add memory cache services
|
||||||
|
builder.Services.AddMemoryCache();
|
||||||
|
builder.Services.AddRouting(options =>
|
||||||
|
{
|
||||||
|
// Replace the type and the name used to refer to it with your own
|
||||||
|
// IOutboundParameterTransformer implementation
|
||||||
|
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddMvc(options =>
|
||||||
|
{
|
||||||
|
options.Conventions.Add(new RouteTokenTransformerConvention(
|
||||||
|
new SlugifyParameterTransformer()));
|
||||||
|
|
||||||
|
});
|
||||||
|
builder.Services.AddControllersWithViews();
|
||||||
|
builder.Services.AddRazorPages(options =>
|
||||||
|
{
|
||||||
|
options.Conventions.AuthorizePage("/Basket/Checkout");
|
||||||
|
});
|
||||||
|
builder.Services.AddHttpContextAccessor();
|
||||||
|
builder.Services
|
||||||
|
.AddHealthChecks()
|
||||||
|
.AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
|
||||||
|
.AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
|
||||||
|
builder.Services.Configure<ServiceConfig>(config =>
|
||||||
|
{
|
||||||
|
config.Services = new List<ServiceDescriptor>(builder.Services);
|
||||||
|
config.Path = "/allservices";
|
||||||
|
});
|
||||||
|
|
||||||
|
// blazor configuration
|
||||||
|
var configSection = builder.Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
||||||
|
builder.Services.Configure<BaseUrlConfiguration>(configSection);
|
||||||
|
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
|
||||||
|
|
||||||
|
// Blazor Admin Required Services for Prerendering
|
||||||
|
builder.Services.AddScoped<HttpClient>(s => new HttpClient
|
||||||
|
{
|
||||||
|
BaseAddress = new Uri(baseUrlConfig.WebBase)
|
||||||
|
});
|
||||||
|
|
||||||
|
// add blazor services
|
||||||
|
builder.Services.AddBlazoredLocalStorage();
|
||||||
|
builder.Services.AddServerSideBlazor();
|
||||||
|
|
||||||
|
|
||||||
|
builder.Services.AddScoped<ToastService>();
|
||||||
|
builder.Services.AddScoped<HttpService>();
|
||||||
|
builder.Services.AddBlazorServices();
|
||||||
|
|
||||||
|
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
|
||||||
|
|
||||||
|
//_services = services; // used to debug registered services
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.Logger.LogInformation("App created...");
|
||||||
|
|
||||||
|
var catalogBaseUrl = builder.Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string;
|
||||||
|
if (!string.IsNullOrEmpty(catalogBaseUrl))
|
||||||
|
{
|
||||||
|
app.Use((context, next) =>
|
||||||
|
{
|
||||||
|
context.Request.PathBase = new PathString(catalogBaseUrl);
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseHealthChecks("/health",
|
||||||
|
new HealthCheckOptions
|
||||||
|
{
|
||||||
|
ResponseWriter = async (context, report) =>
|
||||||
|
{
|
||||||
|
var result = new
|
||||||
|
{
|
||||||
|
status = report.Status.ToString(),
|
||||||
|
errors = report.Entries.Select(e => new
|
||||||
|
{
|
||||||
|
key = e.Key,
|
||||||
|
value = Enum.GetName(typeof(HealthStatus), e.Value.Status)
|
||||||
|
})
|
||||||
|
}.ToJson();
|
||||||
|
context.Response.ContentType = MediaTypeNames.Application.Json;
|
||||||
|
await context.Response.WriteAsync(result);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (app.Environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
app.Logger.LogInformation("Adding Development middleware...");
|
||||||
|
app.UseDeveloperExceptionPage();
|
||||||
|
app.UseShowAllServicesMiddleware();
|
||||||
|
app.UseMigrationsEndPoint();
|
||||||
|
app.UseWebAssemblyDebugging();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
app.Logger.LogInformation("Adding non-Development middleware...");
|
||||||
|
app.UseExceptionHandler("/Error");
|
||||||
|
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||||
|
app.UseHsts();
|
||||||
|
}
|
||||||
|
|
||||||
|
app.UseHttpsRedirection();
|
||||||
|
app.UseBlazorFrameworkFiles();
|
||||||
|
app.UseStaticFiles();
|
||||||
|
app.UseRouting();
|
||||||
|
|
||||||
|
app.UseCookiePolicy();
|
||||||
|
app.UseAuthentication();
|
||||||
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
app.UseEndpoints(endpoints =>
|
||||||
|
{
|
||||||
|
endpoints.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
|
||||||
|
endpoints.MapRazorPages();
|
||||||
|
endpoints.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
|
||||||
|
endpoints.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
|
||||||
|
//endpoints.MapBlazorHub("/admin");
|
||||||
|
endpoints.MapFallbackToFile("index.html");
|
||||||
|
});
|
||||||
|
|
||||||
|
app.Logger.LogInformation("Seeding Database...");
|
||||||
|
|
||||||
|
using (var scope = app.Services.CreateScope())
|
||||||
|
{
|
||||||
|
var scopedProvider = scope.ServiceProvider;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var catalogContext = services.GetRequiredService<CatalogContext>();
|
var catalogContext = scopedProvider.GetRequiredService<CatalogContext>();
|
||||||
await CatalogContextSeed.SeedAsync(catalogContext, loggerFactory);
|
await CatalogContextSeed.SeedAsync(catalogContext, app.Logger);
|
||||||
|
|
||||||
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
|
var userManager = scopedProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||||
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
|
var roleManager = scopedProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||||
await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager);
|
await AppIdentityDbContextSeed.SeedAsync(userManager, roleManager);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
var logger = loggerFactory.CreateLogger<Program>();
|
app.Logger.LogError(ex, "An error occurred seeding the DB.");
|
||||||
logger.LogError(ex, "An error occurred seeding the DB.");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host.Run();
|
app.Logger.LogInformation("LAUNCHING");
|
||||||
}
|
app.Run();
|
||||||
|
|
||||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
|
||||||
Host.CreateDefaultBuilder(args)
|
|
||||||
.ConfigureWebHostDefaults(webBuilder =>
|
|
||||||
{
|
|
||||||
webBuilder.UseStartup<Startup>();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,241 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Net.Http;
|
|
||||||
using System.Net.Mime;
|
|
||||||
using Ardalis.ListStartupServices;
|
|
||||||
using BlazorAdmin;
|
|
||||||
using BlazorAdmin.Services;
|
|
||||||
using Blazored.LocalStorage;
|
|
||||||
using BlazorShared;
|
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
||||||
using Microsoft.AspNetCore.Builder;
|
|
||||||
using Microsoft.AspNetCore.DataProtection;
|
|
||||||
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.AspNetCore.Identity;
|
|
||||||
using Microsoft.AspNetCore.Mvc.ApplicationModels;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
|
||||||
using Microsoft.eShopWeb.Web.Configuration;
|
|
||||||
using Microsoft.eShopWeb.Web.HealthChecks;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.Web;
|
|
||||||
|
|
||||||
public class Startup
|
|
||||||
{
|
|
||||||
private IServiceCollection _services;
|
|
||||||
|
|
||||||
public Startup(IConfiguration configuration)
|
|
||||||
{
|
|
||||||
Configuration = configuration;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IConfiguration Configuration { get; }
|
|
||||||
|
|
||||||
public void ConfigureDevelopmentServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// use in-memory database
|
|
||||||
ConfigureInMemoryDatabases(services);
|
|
||||||
|
|
||||||
// use real database
|
|
||||||
//ConfigureProductionServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureDockerServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddDataProtection()
|
|
||||||
.SetApplicationName("eshopwebmvc")
|
|
||||||
.PersistKeysToFileSystem(new DirectoryInfo(@"./"));
|
|
||||||
|
|
||||||
ConfigureDevelopmentServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ConfigureInMemoryDatabases(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// use in-memory database
|
|
||||||
services.AddDbContext<CatalogContext>(c =>
|
|
||||||
c.UseInMemoryDatabase("Catalog"));
|
|
||||||
|
|
||||||
// Add Identity DbContext
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
|
||||||
options.UseInMemoryDatabase("Identity"));
|
|
||||||
|
|
||||||
ConfigureServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureProductionServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
// use real database
|
|
||||||
// Requires LocalDB which can be installed with SQL Server Express 2016
|
|
||||||
// https://www.microsoft.com/en-us/download/details.aspx?id=54284
|
|
||||||
services.AddDbContext<CatalogContext>(c =>
|
|
||||||
c.UseSqlServer(Configuration.GetConnectionString("CatalogConnection")));
|
|
||||||
|
|
||||||
// Add Identity DbContext
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
|
||||||
options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));
|
|
||||||
|
|
||||||
ConfigureServices(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void ConfigureTestingServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
ConfigureInMemoryDatabases(services);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to add services to the container.
|
|
||||||
public void ConfigureServices(IServiceCollection services)
|
|
||||||
{
|
|
||||||
services.AddCookieSettings();
|
|
||||||
|
|
||||||
|
|
||||||
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
|
||||||
.AddCookie(options =>
|
|
||||||
{
|
|
||||||
options.Cookie.HttpOnly = true;
|
|
||||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
|
||||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
|
||||||
});
|
|
||||||
|
|
||||||
services.AddIdentity<ApplicationUser, IdentityRole>()
|
|
||||||
.AddDefaultUI()
|
|
||||||
.AddEntityFrameworkStores<AppIdentityDbContext>()
|
|
||||||
.AddDefaultTokenProviders();
|
|
||||||
|
|
||||||
services.AddScoped<ITokenClaimsService, IdentityTokenClaimService>();
|
|
||||||
|
|
||||||
services.AddCoreServices(Configuration);
|
|
||||||
services.AddWebServices(Configuration);
|
|
||||||
|
|
||||||
// Add memory cache services
|
|
||||||
services.AddMemoryCache();
|
|
||||||
services.AddRouting(options =>
|
|
||||||
{
|
|
||||||
// Replace the type and the name used to refer to it with your own
|
|
||||||
// IOutboundParameterTransformer implementation
|
|
||||||
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
|
|
||||||
});
|
|
||||||
services.AddMvc(options =>
|
|
||||||
{
|
|
||||||
options.Conventions.Add(new RouteTokenTransformerConvention(
|
|
||||||
new SlugifyParameterTransformer()));
|
|
||||||
|
|
||||||
});
|
|
||||||
services.AddControllersWithViews();
|
|
||||||
services.AddRazorPages(options =>
|
|
||||||
{
|
|
||||||
options.Conventions.AuthorizePage("/Basket/Checkout");
|
|
||||||
});
|
|
||||||
services.AddHttpContextAccessor();
|
|
||||||
services
|
|
||||||
.AddHealthChecks()
|
|
||||||
.AddCheck<ApiHealthCheck>("api_health_check", tags: new[] { "apiHealthCheck" })
|
|
||||||
.AddCheck<HomePageHealthCheck>("home_page_health_check", tags: new[] { "homePageHealthCheck" });
|
|
||||||
services.Configure<ServiceConfig>(config =>
|
|
||||||
{
|
|
||||||
config.Services = new List<ServiceDescriptor>(services);
|
|
||||||
|
|
||||||
config.Path = "/allservices";
|
|
||||||
});
|
|
||||||
|
|
||||||
var configSection = Configuration.GetRequiredSection(BaseUrlConfiguration.CONFIG_NAME);
|
|
||||||
services.Configure<BaseUrlConfiguration>(configSection);
|
|
||||||
var baseUrlConfig = configSection.Get<BaseUrlConfiguration>();
|
|
||||||
|
|
||||||
// Blazor Admin Required Services for Prerendering
|
|
||||||
services.AddScoped<HttpClient>(s => new HttpClient
|
|
||||||
{
|
|
||||||
BaseAddress = new Uri(baseUrlConfig.WebBase)
|
|
||||||
});
|
|
||||||
|
|
||||||
// add blazor services
|
|
||||||
services.AddBlazoredLocalStorage();
|
|
||||||
services.AddServerSideBlazor();
|
|
||||||
|
|
||||||
|
|
||||||
services.AddScoped<ToastService>();
|
|
||||||
services.AddScoped<HttpService>();
|
|
||||||
services.AddBlazorServices();
|
|
||||||
|
|
||||||
services.AddDatabaseDeveloperPageExceptionFilter();
|
|
||||||
|
|
||||||
_services = services; // used to debug registered services
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
|
||||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
|
||||||
{
|
|
||||||
var catalogBaseUrl = Configuration.GetValue(typeof(string), "CatalogBaseUrl") as string;
|
|
||||||
if (!string.IsNullOrEmpty(catalogBaseUrl))
|
|
||||||
{
|
|
||||||
app.Use((context, next) =>
|
|
||||||
{
|
|
||||||
context.Request.PathBase = new PathString(catalogBaseUrl);
|
|
||||||
return next();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
app.UseHealthChecks("/health",
|
|
||||||
new HealthCheckOptions
|
|
||||||
{
|
|
||||||
ResponseWriter = async (context, report) =>
|
|
||||||
{
|
|
||||||
var result = new
|
|
||||||
{
|
|
||||||
status = report.Status.ToString(),
|
|
||||||
errors = report.Entries.Select(e => new
|
|
||||||
{
|
|
||||||
key = e.Key,
|
|
||||||
value = Enum.GetName(typeof(HealthStatus), e.Value.Status)
|
|
||||||
})
|
|
||||||
}.ToJson();
|
|
||||||
context.Response.ContentType = MediaTypeNames.Application.Json;
|
|
||||||
await context.Response.WriteAsync(result);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
if (env.IsDevelopment())
|
|
||||||
{
|
|
||||||
app.UseDeveloperExceptionPage();
|
|
||||||
app.UseShowAllServicesMiddleware();
|
|
||||||
app.UseMigrationsEndPoint();
|
|
||||||
app.UseWebAssemblyDebugging();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
app.UseExceptionHandler("/Error");
|
|
||||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
|
||||||
app.UseHsts();
|
|
||||||
}
|
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
|
||||||
app.UseBlazorFrameworkFiles();
|
|
||||||
app.UseStaticFiles();
|
|
||||||
app.UseRouting();
|
|
||||||
|
|
||||||
app.UseCookiePolicy();
|
|
||||||
app.UseAuthentication();
|
|
||||||
app.UseAuthorization();
|
|
||||||
|
|
||||||
app.UseEndpoints(endpoints =>
|
|
||||||
{
|
|
||||||
endpoints.MapControllerRoute("default", "{controller:slugify=Home}/{action:slugify=Index}/{id?}");
|
|
||||||
endpoints.MapRazorPages();
|
|
||||||
endpoints.MapHealthChecks("home_page_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("homePageHealthCheck") });
|
|
||||||
endpoints.MapHealthChecks("api_health_check", new HealthCheckOptions { Predicate = check => check.Tags.Contains("apiHealthCheck") });
|
|
||||||
//endpoints.MapBlazorHub("/admin");
|
|
||||||
endpoints.MapFallbackToFile("index.html");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -2,23 +2,17 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<RootNamespace>Microsoft.eShopWeb.Web</RootNamespace>
|
<RootNamespace>Microsoft.eShopWeb.Web</RootNamespace>
|
||||||
<UserSecretsId>aspnet-Web2-1FA3F72E-E7E3-4360-9E49-1CCCD7FE85F7</UserSecretsId>
|
<UserSecretsId>aspnet-Web2-1FA3F72E-E7E3-4360-9E49-1CCCD7FE85F7</UserSecretsId>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>latest</LangVersion>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Compile Remove="Catalog\**" />
|
|
||||||
<Content Remove="Catalog\**" />
|
|
||||||
<EmbeddedResource Remove="Catalog\**" />
|
|
||||||
<None Remove="Catalog\**" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Content Remove="compilerconfig.json" />
|
<Content Remove="compilerconfig.json" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Ardalis.ApiEndpoints" Version="3.1.0" />
|
<PackageReference Include="Ardalis.ApiEndpoints" Version="3.1.0" />
|
||||||
<PackageReference Include="Ardalis.ListStartupServices" Version="1.1.3" />
|
<PackageReference Include="Ardalis.ListStartupServices" Version="1.1.3" />
|
||||||
|
|||||||
@@ -1,78 +1,43 @@
|
|||||||
using System;
|
using Microsoft.AspNetCore.Hosting;
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Identity;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
using Microsoft.eShopWeb.Infrastructure.Data;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
using Microsoft.eShopWeb.Infrastructure.Identity;
|
||||||
using Microsoft.eShopWeb.PublicApi;
|
using Microsoft.eShopWeb.PublicApi.AuthEndpoints;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.FunctionalTests.PublicApi;
|
namespace Microsoft.eShopWeb.FunctionalTests.PublicApi;
|
||||||
|
|
||||||
public class ApiTestFixture : WebApplicationFactory<Startup>
|
public class TestApiApplication : WebApplicationFactory<Authenticate>
|
||||||
{
|
{
|
||||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
private readonly string _environment = "Testing";
|
||||||
{
|
|
||||||
builder.UseEnvironment("Testing");
|
|
||||||
|
|
||||||
|
protected override IHost CreateHost(IHostBuilder builder)
|
||||||
|
{
|
||||||
|
builder.UseEnvironment(_environment);
|
||||||
|
|
||||||
|
// Add mock/test services to the builder here
|
||||||
builder.ConfigureServices(services =>
|
builder.ConfigureServices(services =>
|
||||||
{
|
{
|
||||||
services.AddEntityFrameworkInMemoryDatabase();
|
services.AddScoped(sp =>
|
||||||
|
|
||||||
// Create a new service provider.
|
|
||||||
var provider = services
|
|
||||||
.AddEntityFrameworkInMemoryDatabase()
|
|
||||||
.BuildServiceProvider();
|
|
||||||
|
|
||||||
// Add a database context (ApplicationDbContext) using an in-memory
|
|
||||||
// database for testing.
|
|
||||||
services.AddDbContext<CatalogContext>(options =>
|
|
||||||
{
|
{
|
||||||
options.UseInMemoryDatabase("InMemoryDbForTesting");
|
// Replace SQLite with in-memory database for tests
|
||||||
options.UseInternalServiceProvider(provider);
|
return new DbContextOptionsBuilder<CatalogContext>()
|
||||||
|
.UseInMemoryDatabase("DbForPublicApi")
|
||||||
|
.UseApplicationServiceProvider(sp)
|
||||||
|
.Options;
|
||||||
|
});
|
||||||
|
services.AddScoped(sp =>
|
||||||
|
{
|
||||||
|
// Replace SQLite with in-memory database for tests
|
||||||
|
return new DbContextOptionsBuilder<AppIdentityDbContext>()
|
||||||
|
.UseInMemoryDatabase("IdentityDbForPublicApi")
|
||||||
|
.UseApplicationServiceProvider(sp)
|
||||||
|
.Options;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
return base.CreateHost(builder);
|
||||||
{
|
|
||||||
options.UseInMemoryDatabase("Identity");
|
|
||||||
options.UseInternalServiceProvider(provider);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Build the service provider.
|
|
||||||
var sp = services.BuildServiceProvider();
|
|
||||||
|
|
||||||
// Create a scope to obtain a reference to the database
|
|
||||||
// context (ApplicationDbContext).
|
|
||||||
using (var scope = sp.CreateScope())
|
|
||||||
{
|
|
||||||
var scopedServices = scope.ServiceProvider;
|
|
||||||
var db = scopedServices.GetRequiredService<CatalogContext>();
|
|
||||||
var loggerFactory = scopedServices.GetRequiredService<ILoggerFactory>();
|
|
||||||
|
|
||||||
var logger = scopedServices
|
|
||||||
.GetRequiredService<ILogger<ApiTestFixture>>();
|
|
||||||
|
|
||||||
// Ensure the database is created.
|
|
||||||
db.Database.EnsureCreated();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Seed the database with test data.
|
|
||||||
CatalogContextSeed.SeedAsync(db, loggerFactory).Wait();
|
|
||||||
|
|
||||||
// seed sample user data
|
|
||||||
var userManager = scopedServices.GetRequiredService<UserManager<ApplicationUser>>();
|
|
||||||
var roleManager = scopedServices.GetRequiredService<RoleManager<IdentityRole>>();
|
|
||||||
AppIdentityDbContextSeed.SeedAsync(userManager, roleManager).Wait();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, $"An error occurred seeding the " +
|
|
||||||
"database with test messages. Error: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,11 +10,11 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class AuthenticateEndpoint : IClassFixture<ApiTestFixture>
|
public class AuthenticateEndpoint : IClassFixture<TestApiApplication>
|
||||||
{
|
{
|
||||||
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||||
|
|
||||||
public AuthenticateEndpoint(ApiTestFixture factory)
|
public AuthenticateEndpoint(TestApiApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class ApiCatalogControllerList : IClassFixture<ApiTestFixture>
|
public class ApiCatalogControllerList : IClassFixture<TestApiApplication>
|
||||||
{
|
{
|
||||||
public ApiCatalogControllerList(ApiTestFixture factory)
|
public ApiCatalogControllerList(TestApiApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class CreateEndpoint : IClassFixture<ApiTestFixture>
|
public class CreateEndpoint : IClassFixture<TestApiApplication>
|
||||||
{
|
{
|
||||||
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||||
private int _testBrandId = 1;
|
private int _testBrandId = 1;
|
||||||
@@ -21,7 +21,7 @@ public class CreateEndpoint : IClassFixture<ApiTestFixture>
|
|||||||
private string _testName = "test name";
|
private string _testName = "test name";
|
||||||
private decimal _testPrice = 1.23m;
|
private decimal _testPrice = 1.23m;
|
||||||
|
|
||||||
public CreateEndpoint(ApiTestFixture factory)
|
public CreateEndpoint(TestApiApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class DeleteEndpoint : IClassFixture<ApiTestFixture>
|
public class DeleteEndpoint : IClassFixture<TestApiApplication>
|
||||||
{
|
{
|
||||||
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||||
|
|
||||||
public DeleteEndpoint(ApiTestFixture factory)
|
public DeleteEndpoint(TestApiApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class GetByIdEndpoint : IClassFixture<ApiTestFixture>
|
public class GetByIdEndpoint : IClassFixture<TestApiApplication>
|
||||||
{
|
{
|
||||||
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||||||
|
|
||||||
public GetByIdEndpoint(ApiTestFixture factory)
|
public GetByIdEndpoint(TestApiApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class AccountControllerSignIn : IClassFixture<WebTestFixture>
|
public class AccountControllerSignIn : IClassFixture<TestApplication>
|
||||||
{
|
{
|
||||||
public AccountControllerSignIn(WebTestFixture factory)
|
public AccountControllerSignIn(TestApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class CatalogControllerIndex : IClassFixture<WebTestFixture>
|
public class CatalogControllerIndex : IClassFixture<TestApplication>
|
||||||
{
|
{
|
||||||
public CatalogControllerIndex(WebTestFixture factory)
|
public CatalogControllerIndex(TestApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class OrderIndexOnGet : IClassFixture<WebTestFixture>
|
public class OrderIndexOnGet : IClassFixture<TestApplication>
|
||||||
{
|
{
|
||||||
public OrderIndexOnGet(WebTestFixture factory)
|
public OrderIndexOnGet(TestApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.WebRazorPages;
|
namespace Microsoft.eShopWeb.FunctionalTests.WebRazorPages;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class BasketPageCheckout : IClassFixture<WebTestFixture>
|
public class BasketPageCheckout : IClassFixture<TestApplication>
|
||||||
{
|
{
|
||||||
public BasketPageCheckout(WebTestFixture factory)
|
public BasketPageCheckout(TestApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ using Xunit;
|
|||||||
namespace Microsoft.eShopWeb.FunctionalTests.WebRazorPages;
|
namespace Microsoft.eShopWeb.FunctionalTests.WebRazorPages;
|
||||||
|
|
||||||
[Collection("Sequential")]
|
[Collection("Sequential")]
|
||||||
public class HomePageOnGet : IClassFixture<WebTestFixture>
|
public class HomePageOnGet : IClassFixture<TestApplication>
|
||||||
{
|
{
|
||||||
public HomePageOnGet(WebTestFixture factory)
|
public HomePageOnGet(TestApplication factory)
|
||||||
{
|
{
|
||||||
Client = factory.CreateClient();
|
Client = factory.CreateClient();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,74 +5,42 @@ using Microsoft.AspNetCore.Mvc.Testing;
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Data;
|
using Microsoft.eShopWeb.Infrastructure.Data;
|
||||||
using Microsoft.eShopWeb.Infrastructure.Identity;
|
using Microsoft.eShopWeb.Infrastructure.Identity;
|
||||||
using Microsoft.eShopWeb.Web;
|
using Microsoft.eShopWeb.Web.Interfaces;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace Microsoft.eShopWeb.FunctionalTests.Web;
|
namespace Microsoft.eShopWeb.FunctionalTests.Web;
|
||||||
|
|
||||||
public class WebTestFixture : WebApplicationFactory<Startup>
|
public class TestApplication : WebApplicationFactory<IBasketViewModelService>
|
||||||
{
|
{
|
||||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
private readonly string _environment = "Development";
|
||||||
{
|
|
||||||
builder.UseEnvironment("Testing");
|
|
||||||
|
|
||||||
|
protected override IHost CreateHost(IHostBuilder builder)
|
||||||
|
{
|
||||||
|
builder.UseEnvironment(_environment);
|
||||||
|
|
||||||
|
// Add mock/test services to the builder here
|
||||||
builder.ConfigureServices(services =>
|
builder.ConfigureServices(services =>
|
||||||
{
|
{
|
||||||
services.AddEntityFrameworkInMemoryDatabase();
|
services.AddScoped(sp =>
|
||||||
|
|
||||||
// Create a new service provider.
|
|
||||||
var provider = services
|
|
||||||
.AddEntityFrameworkInMemoryDatabase()
|
|
||||||
.BuildServiceProvider();
|
|
||||||
|
|
||||||
// Add a database context (ApplicationDbContext) using an in-memory
|
|
||||||
// database for testing.
|
|
||||||
services.AddDbContext<CatalogContext>(options =>
|
|
||||||
{
|
{
|
||||||
options.UseInMemoryDatabase("InMemoryDbForTesting");
|
// Replace SQLite with in-memory database for tests
|
||||||
options.UseInternalServiceProvider(provider);
|
return new DbContextOptionsBuilder<CatalogContext>()
|
||||||
|
.UseInMemoryDatabase("InMemoryDbForTesting")
|
||||||
|
.UseApplicationServiceProvider(sp)
|
||||||
|
.Options;
|
||||||
|
});
|
||||||
|
services.AddScoped(sp =>
|
||||||
|
{
|
||||||
|
// Replace SQLite with in-memory database for tests
|
||||||
|
return new DbContextOptionsBuilder<AppIdentityDbContext>()
|
||||||
|
.UseInMemoryDatabase("Identity")
|
||||||
|
.UseApplicationServiceProvider(sp)
|
||||||
|
.Options;
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
services.AddDbContext<AppIdentityDbContext>(options =>
|
return base.CreateHost(builder);
|
||||||
{
|
|
||||||
options.UseInMemoryDatabase("Identity");
|
|
||||||
options.UseInternalServiceProvider(provider);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Build the service provider.
|
|
||||||
var sp = services.BuildServiceProvider();
|
|
||||||
|
|
||||||
// Create a scope to obtain a reference to the database
|
|
||||||
// context (ApplicationDbContext).
|
|
||||||
using (var scope = sp.CreateScope())
|
|
||||||
{
|
|
||||||
var scopedServices = scope.ServiceProvider;
|
|
||||||
var db = scopedServices.GetRequiredService<CatalogContext>();
|
|
||||||
var loggerFactory = scopedServices.GetRequiredService<ILoggerFactory>();
|
|
||||||
|
|
||||||
var logger = scopedServices
|
|
||||||
.GetRequiredService<ILogger<WebTestFixture>>();
|
|
||||||
|
|
||||||
// Ensure the database is created.
|
|
||||||
db.Database.EnsureCreated();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Seed the database with test data.
|
|
||||||
CatalogContextSeed.SeedAsync(db, loggerFactory).Wait();
|
|
||||||
|
|
||||||
// seed sample user data
|
|
||||||
var userManager = scopedServices.GetRequiredService<UserManager<ApplicationUser>>();
|
|
||||||
var roleManager = scopedServices.GetRequiredService<RoleManager<IdentityRole>>();
|
|
||||||
AppIdentityDbContextSeed.SeedAsync(userManager, roleManager).Wait();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, $"An error occurred seeding the " +
|
|
||||||
"database with test messages. Error: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user