Code Monkey home page Code Monkey logo

fullstackhero / dotnet-webapi-starter-kit Goto Github PK

View Code? Open in Web Editor NEW
4.0K 138.0 1.3K 3.36 MB

production grade .net 8 webapi starter kit with multitenancy support and clean code. ๐Ÿ”ฅ

Home Page: https://fullstackhero.net/dotnet-webapi-boilerplate/

License: MIT License

C# 93.86% HTML 1.67% PowerShell 0.72% Vim Snippet 1.97% Makefile 0.21% Shell 0.08% HCL 1.49%
clean-architecture dotnet webapi multitenancy boilerplate template fullstackhero codewithmukesh clean-architechture dotnet8

dotnet-webapi-starter-kit's People

Contributors

274188a avatar akema-trebla avatar alex0403lin avatar b-virtual avatar baranacikgoz avatar cetindogu avatar chhinsras avatar chihabhajji avatar chrbos avatar dependabot[bot] avatar frankyjquintero avatar fretje avatar geekz-reno avatar gialan avatar iammukeshm avatar ittyabrehman avatar juststeve avatar marcelo-maciel avatar mikaelhild avatar mluepkes avatar musmanrafiq avatar nikolasivkov avatar pashaie avatar pedroventura235 avatar pedroventurawork avatar snax4a avatar tj-styr avatar trihugger avatar xlogex avatar zigimun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotnet-webapi-starter-kit's Issues

Configurable Swagger Support

@iammukeshm recently I was working on a private project with a US client. where the requirement is to build an ERP SAAS application that will be deployed on multiple servers with a load balancer. The client wants to expose the swagger doc on few instances of an application in some regions because of some business purposes. On the basics of this scenario, I think we should also add support to enable/disable the swagger according to the appSettings.json configuration.

Enhance Multitenancy Workflow

Current Multitenant Implementation takes tenant details from AppSettings. It's better to have these settings stored in the Database and cache them to application memory.

  • Move to a Database Managed Tenant Approach.
  • Create a Root User who has access to manage tenants.
  • Root user should also be a tenant himself.
  • Introduce Caching in Tenant Service
  • Tenant Creation
  • Tenant Validity in Months -> after which tenant users won't have access to the system
  • Tenant Status - Active / Inactive
  • Only Root User has access to tenant management

The remaining flow remains the same as it is now.

Adding ApplicationUser as Navigation Property to entities

Discussed in #127

Originally posted by pashaie November 2, 2021
Hi,
In Onion Architecture we are supposed to put entities in Domain layer. But ApplicationUser is on Infrastructure layer and that prevents us from adding ApplicationUser as Navigation Property to entities. Is there any best practice for doing it?

Create project without multitenancy

Is your feature request related to a problem? Please describe.
I want to use FSH without tenant, the problem is you should send always header with tenant key and always tenant service work with every service and get connection strings

Describe the solution you'd like
create two templates or make an option to disable tenant

thanks

Database Sharding Plan

Hi,

Have you considered about database sharding plan? If you've planned to support it, I've read that you primarily support PostgreSQL, and Citus Data is one of the sharding solution for it.

According to Citus docs, one of the requirements is to have composite primary keys:

http://docs.citusdata.com/en/v10.1/use_cases/multi_tenant.html#preparing-tables-and-ingesting-data

But it seems that your Dtos are based on a single primary key:

https://github.com/fullstackhero/dotnet-webapi-boilerplate/blob/main/src/Shared/Shared.DTOs/Catalog/ProductDetailsDto.cs

What do you think about this? Thanks

Add [AllowAnonymous] on create tenant not working

Describe the bug
Its possible to create tenant without doing any authentication?

To Reproduce
Steps to reproduce the behavior:
Change [MustHavePermission(RootPermissions.Tenants.Create)] to [AllowAnonymous] on TenantController -> CreateAsync, still return unauthorized

Expected behavior
Create tenant without perform any authentication

Add File Storage Service

  • FileStorage Interface
  • LocalFileStorage Implementation
  • Allow Static File Serving
  • Entity Based Folders
  • Product Image Demo

Swagger Setup

  • Code Separation via Extensions
  • Custom Swagger
  • JWT Auth Support

Redis Support

  • Option to support Redis Server in Production
  • Include in Docker Composes

Extensions Cleanup

  • Separate Extensions Physically on the basis of what they do - Helps improve code readability

Brands Controller

Describe the bug

  1. In Postman, the get-brands function does not work with and without parameters.
  2. Create a new brand and specify the brand's name and description.
    Then just update the brand name by deleting the brand definition. (The brand definition is required to be null by the user) In this case, the api gives an error "Object reference not set to an instance of an object".

To Reproduce
Steps to reproduce the behavior:

  1. Run the Catalog/get-brands function with Postman.
  2. Build Brand. (Enter name and description)
    Update Brand (Keep the name the same, delete the description)
    Brand Update (Keep the name the same, write a new description)

Expected behavior

  1. I think it should fetch the brand list with the pagination parameter.
  2. I think the new values โ€‹โ€‹of the brand should be saved in the database.

Desktop (please complete the following information):
Postman

I'm sorry for my bad english.

new Solution does not build when creating from visual studio template

Describe the bug
Try to build a new sln created from template get a build error in the domain and shared projects about sytlecop.json could not be found

To Reproduce
Steps to reproduce the behavior:
create a new sln from the visual studio FullStackHero WebAPI Boilerplate

Expected behavior
sln should build

Error seeding the database

Describe the bug
EF complains the databases does not exist. -Migrations should be applied before seeding.
Also the the index on Identity.Roles [NormalizedName] is Unique and will prevent same RoleName even per Tenant when seeding the db.

To Reproduce
Steps to reproduce the behavior:

  1. run 'update-database'

Suggestion
Remove index on NormalizedName and add unique index on {normalizedname,tenantId}

Refresh token missing property

Hi :)

Bug description

While working with refresh token, I've found out that in GetPrincipalFromExpiredToken() function, property ValidateLifetime should be set to false when creating TokenValidationParameters instance.

How to fix

  1. Go to https://github.com/fullstackhero/dotnet-webapi-boilerplate/blob/d907cacdb6534fe1053ced6da0fc2a5c869df013/src/Infrastructure/Identity/Services/TokenService.cs#L169
  2. Extend tokenValidationParameters variable with ValidateLifetime = false

Add Mapster support for object mappings

Please add the Mapster for object mapping as it is much efficient on both speed and memory. We could gain a 4x performance improvement while using only 1/3 of memory. we don't need to write our own DTO classes. Mapster provides Mapster. Tool to help us generating models. And if we would like to have explicit mapping, Mapster also generates a mapper class for us.

Mapster Repository URL:
https://github.com/MapsterMapper/Mapster

Error when removing-migration

Describe the bug
An error occurs when removing a previous created migration.
Error: A relational store has been configured without specifying either the DbConnection or connection string to use.

To Reproduce
Steps to reproduce the behavior:

  1. Open Package Manger Console in Visual Studio
  2. Create a new migration using the following command:
    add-migration AddSortOrder -context ApplicationDbContext -project Migrators.MSSQL -outputdir Migrations\Application -args "--provider SqlServer"
  3. Remove migration using the following command:
    remove-migration -context ApplicationDbContext -project Migrators.MSSQL -args "--provider SqlServer"
  4. Following error occurs:

System.InvalidOperationException: A relational store has been configured without specifying either the DbConnection or connection string to use.
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.b__0(DateTime giveUp)
at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_02.<Execute>b__0(DbContext c, TState s) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 operation, Func2 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 operation)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.GetAppliedMigrations()
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.RemoveMigration(String projectDir, String rootNamespace, Boolean force, String language)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.RemoveMigration(String contextType, Boolean force)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigrationImpl(String contextType, Boolean force)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.RemoveMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
A relational store has been configured without specifying either the DbConnection or connection string to use.

Expected behavior
Migration is removed.

Screenshots
image

Desktop (please complete the following information):

  • Windows 10

Multi Tenant - ApplicationDbContext on BackgroundJob, Worker or isolated process: Example HangFire

The use of the 'contextdb' within an isolated process presents conflicts since the whole definition depends on the httpContext for some internal processes such as audit or multiple tenant (ITenantService tenantService, ICurrentUser currentUserService)

https://github.com/fullstackhero/dotnet-webapi-boilerplate/blob/ef53f36f419a2817c57381719cf77aaafc133f15/src/Infrastructure/Persistence/ApplicationDbContext.cs#L21

The dependency of the httpContext is generated in these processes

https://github.com/fullstackhero/dotnet-webapi-boilerplate/blob/ef53f36f419a2817c57381719cf77aaafc133f15/src/Infrastructure/Services/General/TenantService.cs#L43

https://github.com/fullstackhero/dotnet-webapi-boilerplate/blob/bc433a04013c1b3580f937d7331b4f6fd779b582/src/Infrastructure/Identity/Services/CurrentUser.cs#L14

This step is a great limitation to be able to create isolated or background processes for secondary tasks or Jobs with Hangfire that require an injection of 'ApplicationDbContext' or any of the existing repositories.

I consider that the process of defining tenantId and CurrentUserId should occur in the flow from the application so the services, dbcontext and other dependencies are isolated from the httpcontext layer

PS: in the case of HangFire, an extra solution must be created since achieving tenure from this point requires additional steps such as those mentioned here:

https://stackoverflow.com/questions/57394712/hangfire-multi-tenant-asp-net-core-resolving-the-correct-tenant

It is to clarify that I do not mean to create a database for each hangfire, but to use the dbcontext within it for background tasks which for obvious reasons cannot carry the HTTP context.

https://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html

Example Basic:

BrandGeneratorTask.cs

`public class BrandGeneratorTask {

    private readonly IRepositoryAsync _repository;
    public BrandGeneratorTask(IRepositoryAsync repository)
    {
        _repository = repository;
    }

    [Queue("notdefault")]
    [DisplayName("Generate Random Brand example job on Queue notDefault")]
    public void Execute()
    {
        foreach (int item in Enumerable.Range(0, 100))
        {
            await _repository.CreateAsync<Brand>(new Brand(name: $"Brand Random - {Guid.NewGuid()}", "Funny description"));
        }
        await _repository.SaveChangesAsync();
    }
}`

Call example(representation of the generic call process from the jobservice):

BackgroundJob.Enqueue<BrandGeneratorTask>(x => x.Execute());

It is finally that the process of sending arguments to Hangfire should not be of type ref or out

https://docs.hangfire.io/en/latest/background-methods/passing-arguments.html

https://www.hangfire.io/blog/2014/05/10/are-your-methods-ready-to-run-in-background.html

Support Multiple Key Types for Base Entity

Guid is a secure and reliable data type. But there can be instances where performance can be a bit down due to lot of Guids in DBs.
To combat this, we can make the BaseEntity to BaseEntity where T can be simple ints as well.

Someone can take this up and raise a PR as well.

Things to note.
Ensure new migrations are built.
Test every other scenario as well.

Get-X-By-Id - caching server-side

Describe the bug
Create a new product, and assigned to a particular brand.
Then updated brand name, and resubmitted the request for the product by id. Did not refresh brand name.
The same is true if you update information on the product, it will return the original product not the new updated information.

To Reproduce
Steps to reproduce the behavior:

  1. Create a Brand
  2. Create a Product - assign to previous brand
  3. Get Product by Id
  4. Update Brand name to a new name
  5. Refresh Product by Id

Expected behavior
Should get any updates to the data, not sure if it is being cached to eliminate reloading data, which makes sense, but I feel it should be able to detect data changes.

Desktop (please complete the following information):
Postman

Setup Identity

  • Initial Folder Structure
  • Projects Setup
  • Persistence Setup
  • Token Generation
  • Refresh Tokens
  • User Registrations
  • DB Seeder

Add Default Role with Permissions

Whenever a new user is registered, I need a default role to be assigned to this user.

This role should have some default permissions as well.

INFO: Using VS 2022 Preview

Just in cse anyone else is on the bleeding edge like me

In order to get the code compiling for Visual Studio 2022 (v17.0.0 Preview 4.1) I had to make a few small tweaks:

  1. in the project xml add ImplcitUsings:
    <ImplicitUsings>enable</ImplicitUsings>

  2. at the solution level to set the sdk version by adding a global.json file:
    { "sdk": { "version": "6.0.100-rc.1.21463.6", } }

  • possibly useful to add to the redme.md somewhere?

Can We Add Specification to GetSearchResult

In Pagination Request Can We add includes to GetSearchResult in Repository Class

public async Task<PaginatedResult<TDto>> GetSearchResultsAsync<T, TDto>(int pageNumber, int pageSize = int.MaxValue, string[] orderBy = null, Search advancedSearch = null, string keyword = null, Expression<Func<T, bool>> expression = null,
params string[] includes ,
CancellationToken cancellationToken = default)
        where T : BaseEntity
        where TDto : IDto
        {
            IQueryable<T> query = _dbContext.Set<T>().AsNoTracking();
            if (includes != null)
            {
                foreach (var include in includes)
                {
                    if (include != null)
                        query = query .Include(include);
                }
            }

            if (expression != null) query = query.Where(expression);
            if (advancedSearch?.Fields.Count > 0 && !string.IsNullOrEmpty(advancedSearch.Keyword))
                query = query.AdvancedSearch(advancedSearch);
            else if (!string.IsNullOrEmpty(keyword))
                query = query.SearchByKeyword(keyword);
            string ordering = new OrderByConverter().ConvertBack(orderBy);
            query = !string.IsNullOrWhiteSpace(ordering) ? query.OrderBy(ordering) : query.OrderBy(a => a.Id);
            return await query.ToMappedPaginatedResultAsync<T, TDto>(pageNumber, pageSize);
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.