ASP.NET Core WebAPI – Clean Architecture


An ASP.NET Core WebAPI Solution Template that is built with Loosely-Coupled and Inverted-Dependency/Onion Architecture along with other essential integrations.

Clean Architecture with ASP.NET Core 3.1 WebApi - Swagger

Project Specifications

The Project is currently at v1.1 – Stable Release

Here is what you can expect to get with this release.

ASP.NET Core 3.1 Web API

This is a Standalone ASP.NET Core WebAPI Solution with multiple Layers of Abstraction. The Library Projects are build on .NET Core 3.1 Libraries / .NET Standard 2.1 Libraries.

One-Click Install

This Project comes with a Visual Studio 2019 Solution Template that allows you to start new Projects using the Clean Architecture for WebAPI with ease. That’s a lot of time saved!

Open Source

This Project is licensed under MIT License, which means it is FREE to use , distribute. Feel free to contribute to this project as well. Let’s make this The Best Ever Template for ASP.NET Core 3.1 WebApi!

The Problem this Project Solves

Does it really make sense to Setup your ASP.NET Core Solution everytime you start a new WebApi Project ? Aren’t we wasting quite a lot of time in doing this over and over gain?

This is the exact Problem that I intend to solve with this Full-Fledged ASP.NET Core 3.1 WebApi Solution Template, that also follows various principles of Clean Architecture.

The primary goal is to create a Full-Fledged implementation, that is well documented along with the steps taken to build this Solution from Scratch. This Solution Template will also be available within Visual Studio 2019 (by installing the required Nuget Package / Extension).

  • Demonstrate Clean Monolith Architecture in ASP.NET Core 3.1
  • This is not a Proof of Concept
  • Implementation that is ready for Production
  • Integrate the most essential libraries and packages
Clean Architecture Source Code
Clean Architecture Source Code


  1. Onion Architecture
  2. CQRS with MediatR Library
  3. Entity Framework Core – Code First
  4. Repository Pattern – Generic
  5. MediatR Pipeline Logging & Validation
  6. Serilog
  7. Swagger UI
  8. Response Wrappers
  9. Healthchecks
  10. Pagination
  11. In-Memory Database
  12. Microsoft Identity with JWT Authentication
  13. Role based Authorization
  14. Identity Seeding
  15. Database Seeding 
  16. Custom Exception Handling Middlewares
  17. API Versioning
  18. Fluent Validation
  19. Automapper
  20. SMTP / Mailkit / Sendgrid Email Service
  21. Complete User Management Module (Register / Generate Token / Forgot Password / Confirmation Mail)


Onion / Hexagonal Architecture

The Onion architecture, introduced by Jeffrey Palermo, overcomes the issues of the layered architecture with great ease. With Onion Architecture, the game-changer is that the Domain Layer (Entities and Validation Rules that are common to the business case ) is at the Core of the Entire Application. This means higher flexibility and lesser coupling. In this approach, we can see that all the Layers are dependent only on the Core Layers (Application and Domain Layer is collectively called as the Core Layer).

Onion / Hexagonal Architecture

Everything done for you.

Get the Complete Source Code of this Project here. Feel free to contribute as well. The Steps to get started are mentioned in the next section.

Why ASP.NET Core WebAPI – Clean Architecture?

While getting started with this Project, I could not find any Clean Architecture implementation that is specifically built for ASP.NET Core 3.1 WebAPI.

Starting with a Clean Architecture in quite Important for the lifetime of your applications. You really don’t want to re-engineer you solutions half-way down the development stages, do you?


Every Major Update will be tagged as versioned Release. Included Features and Changes will be made available within the Release Pages.


  • Make sure you are running on the latest .NET Core SDK (SDK 3.1 and above only). Get the latest one here.
  • Visual Studio 2019 ( You can check out my Installation Guide of Visual Studio 2019 Community which is completely Free to use.) Make sure that ASP.NET and web development workload is installed.
  • Install the latest DOTNET & EF CLI Tools by using this command – dotnet tool install –global dotnet-ef 
  • I Recommend that you read Onion Architecture In ASP.NET Core With CQRS – Detailed article to understand this implementation much better. This project is just an Advanced Version of the mentioned article.
  • Once you clear with Onion Architecture Implementation, you will also need to be aware of CQRS MediatR Pattern. I have written a step-by-step guide on how to implement CQRS using MediatR Library. Read it here.

Getting Started

To get started / check out this Boiler Plate Template for Clean Architecture with ASP.NET Core WebApi, there are quite a few ways. Let’s go through them,

1. Using the Visual Studio Project Template

Download the Visual Studio Project Template from Visual Studio Marketplace from here –

cleanArchitecture MarketPlace

Once Installed, Open Visual Studio and Create a New Project. You get to see our newly installed template. Use this Template to Create a new Project.

cleanArchitecture VisualStudio

I created a new Project with the Name, “PointOfSales.Basic”. Here is the Solution Structure that Visual Studio sets up for you. It’s that easy 🙂

cleanArchitecture FolderStructure

After Visual Studio downloads the required packages, all you have to do is to open up appsettings.json, modify your connection string. With that done, Open up Package Manager Console and run the following commands.

update-database -Context IdentityContext
update-database -Context ApplicationDbContext

That’s it. Now Build and Run your New Application! 😀

Clean Architecture with ASP.NET Core 3.1 WebApi - Swagger

2. Or, you can clone the Source Code

Navigate to the Project Repository –

Click on the Code -> Download ZIP, as mentioned below. This will download the entire source code for you locally to your machine (OR) Download the Latest Release from here.

Clean Architecture with ASP.NET Core WebApi

Extract the Zip file and navigate to the Root of the WebAPI Project (Not the Solution File). In this directory, open up Power Shell and run the following commands.

Before proceeding do not forget to open up the appsettings.json and change the connection strings / email settings and so on. Note that you can use separation connection strings for both Identity and Application!

dotnet restore
dotnet ef database update -Context ApplicationDbContext
dotnet ef database update -Context IdentityContext
dotnet run (OR) Run the Solution using Visual Studio 2019

When you run the application, Swagger Opens up. Here you can find the available endpoint.

Folder Structure

Here is how the Solution Folder Looks like.

clean architecture webapi folder structure

1. Core

The Core Layers will never depend on any other layer. Therefore what we do is that we create interfaces in the Application Layer and these interfaces get implemented in the external layers. This is also known and DIP or Dependency Inversion Principle.

It is also important to note that these layers are .NET Standard 2.1 Libraries. This is so because we need to make these layers as comptatible as possible with other projects. Let’s say tommorow your client wants a .NET 4.7 Solutions (quite unlikely though) with the near-same business logics. At such scenarios, .NET Standard Libraries will be of great help.

1.1 Domain

All the Entities and the most common models are available here. Note that this Layer will NEVER depend on anything else.

1.2 Application

Interfaces, CQRS Features, Exceptions, Behaviors are available here.

2. Infrastructure

Whenever there is a requirement to communicate with an external source, we implement it on the Infrastructure Layer. For example, Database or other Services will be included here. To make the separation more visible, We will maintain further sub projects with the naming convention as ‘Infrastructure.xxxxxx’ where xxxxxx is the actual Point of Concern.

2.1 Infrastructure.Identity

In this implementation, we will make use of the already AWESOME Microsoft Identity. Let’s seperate the User Managment Database from the Main Application Database. This is made possible by multiple – DbContext Classes in each of the required Infrastructure Project

2.2 Infrastructure.Persistence

An Application Specific Database will be maintained. This is to ensure that there is no relation between the DBContext classes of Application and the Identity.

2.3 Infrastructure.Shared

Now, there are some services that are common to the other Infrastructure Layers and has the possibility of use in nearly all the Infrastructure Layers. This includes Mail Service, Date Time Service and so on. Thus it is a better Idea to have a shared Infrastructure project as well.

3. WebApi

This is also known as the Presentation Layer, where you would put in the project that the user can interact with. In our case it is the WebAPI Project.

Detailed Layer-By-Layer Documentation

Coming Soon.

Support the Project

Your small contribution can help support the project and motivate me to make frequent updates to this Open Source Project. If you find this Project helpful or you learnt something from here, consider supporting.

Did you like this content? Found this article helpful? Consider Supporting by buying me a coffee.

Buy me a coffee  Buy me a coffee

Also, Leave a Star / Review on
Github –
Visual Studio Marketplace –

This would help me reach this project to the eyes of many more developers around the world! Thanks

Additional Resources

  • Onion Architecture In ASP.NET Core With CQRS – Detailed – We will talk about Onion Architecture In ASP.NET Core and it’s advantages. We will also together build a WebApi that follows a variant of Onion Architecture so that we get to see why it is important to implement such an architecture in your upcoming projects. 
  • CQRS with MediatR in ASP.NET Core 3.1 – Ultimate Guide – Let’s talk about CQRS in ASP.NET Core 3.1 and it’s implementation along with MediatR and Entity Framework Core – Code First Approach. I will implement this pattern on a WebApi Project. The source code of this sample is linked at the end of the post. Of the several design patterns available, CQRS is one of the most commonly used patterns that helps architect the Solution to accommodate the Onion Architecture.


There are a lot of References that I had taken in-order to build up this Solution. Few of them are Jason Taylor, Steve Smith , Nick, and many more. The eShop Repository Series of Microsoft has helped quite a lot.


  1. Akhil Kumar

    Many Thanks for sharing your valuable knowledge…

  2. Arthur Kater

    Hi Mukesh,

    Nice work to put all the pieces together. Thanks!

    Question: How to get add-migration to work? I get the error message “Unable to create an object of type ‘ApplicationDbContext’. For the different patterns supported at design time, see

    • Mukesh Murugan

      Hi Arthur,

      First step, check what the issue is .
      add-migration Added_something -verbose

      Run this command on package manager console. It will pinpoint you to the issue. From there you can debug the issue.
      However, i think this issue is because you have not set the default project properly.
      1. Set API Project as the Staryup project.
      2. Open up package manager console.
      3. There you can see a small dropdown for default project. Choose the project where the specific context class lives.
      Run this then,

      add-migration migration_name -Context IdentityContext

      Try this and let me know.

      Thanks and regards

      • Artyom

        Very interesting, how will you make .net standard libs to work with .net framework 4.7 if 2.1 is not supported even by .net framework 4.8…

  3. sky

    hi mukesh,
    i really appreciate you. can you please work on multi tenant based architectures also. that would be so great. takecare

    • Mukesh Murugan

      Hope you liked this implementation. Will surely work on multi-tenancy as well.

  4. Mark

    Can you also add a new template for ASP.Net core Web Api Including these
    Onion Architecture
    CQRS with MediatR Library
    Dapper (Instead of Entity Framework Core – Code First)
    Repository Pattern – Generic
    MediatR Pipeline Logging & Validation
    Serilog or Nlog
    Swagger UI
    Response Wrappers
    Redis Caching
    In-Memory Database
    Microsoft Identity with JWT Authentication
    Role based Authorization
    Custom Exception Handling Middlewares
    API Versioning
    Fluent Validation
    Fluent mapper
    SMPT / Mailkit / Sendgrid Email Service
    Complete User Management Module (Register / Generate Token / Forgot Password / Confirmation Mail)

    • Mukesh Murugan

      Hi, Thanks for reaching out.

      Yes, I am already working on adding Dapper to this Solution as new Infrastructure Layer, so that you easily switch the ORM whenever you want. Just working on the architecture part.

      Dommel? Have not heard about. Will give it a look though. Will have to check out Fluent Mapper too.

      NLOG/Serilog will be integrated soon.

      Hope you liked the implementation.

      • Arun

        Thanks Mukesh ,
        I really loved the architecture that you have created.
        The only point where i am stuck is using Dapper since i also have SQL stored procedure and for me to implement SP’s are from dapper.


        • Mukesh Murugan

          Hi, Thanks for your feedback.
          You can easily add Dapper in the Infrastructure Layer, by adding a new Infrastructure Project named Infrastructure.Persistence.Dapper or something, and have your dapper implementations there. However, in the next version of this Architecture (v1.1) , I am planning to add this option as well, where users can switch between the ORM.


          • jonas tan

            i would love to see ur approach on ORM swithching. tnx

          • Prabhakar

            Good Work Mukesk!

            I’m expecting on Dapper implementation or Could you guide me by presenting an article for Implementing Dapper Identity at-least.


          • Mukesh Murugan

            Hi, Thanks for the feedback.
            Dapper with Identity can be a bit complicated. I will try to write an article on with along with complete source. Maybe that could help you out as well. Will keep you posted.

  5. Vinicius

    Hi, that is a very interesting architecture.

    Just a quick question:
    I always use the same context for the application and identity, so I can use a join when I want to get the user information that is linked in a entity.
    How would that work in this scenario? I would have to do 2 queries?

    • Mukesh Murugan

      Hi, yes.In cases where you actually need data from the Identity table, you would have to use both these contexts in your call. I guess it is like adding a bit more security and a cleaner separation. However I am still in the process of making this architecture simple and logical to use. What are your thoughts?

      • Vinicius

        I think this may lead to some performance issues.
        For example, if I want to get a list of products with the name of the user that created it I would have to get the list of products, and for each product do a query to get the name of the user.

        I can think of two solutions:
        – Put the ApplicationUser in the ApplicationDbContext as well, as it allows foreign keys for another schemas (at least in SQL Server)
        – Or create another user table in the ApplicationDbContext containing only the necessary information (name, email, etc) so it does not expose all the user data to the application

        • Marcelo

          What about using a store procedure to fetch the data accross databases? In that case we need to add the GUID of the user in AuditableBaseEntity to store it in the Products table and then join with that in the SP. It is a good practice?

  6. martinvzlaa

    Whaiting for The Project is currently at V2 😀

    • Mukesh Murugan

      It’s almost done. The documentation is pending. Will release it by this weekend hopefully, along with the Solution Template which will be available on the Visual Studio Market Place 😀

      • codelover


  7. josep temprano

    Only one question Mukesh, for the database seeding, do you know Bogus? Do you consider it as a good option to use with EF Core?
    Thanks again.

    • Mukesh Murugan

      Yes, Bogus is good option if you want to generate bulk sample data for testing purposes and seed it with efcore. But I think it might be an overkill in this scenario. The ultimate aim is to reduce the number of dependencies. When we can do the essential seeding in code, i really don’t see the need to use bogus. But this is quite a scenario specific requirement.

      • josep temprano

        You are right Mukesh. For this reason I’m waiting your solution for seeding in code. It will be interesting to seed more than one related entities to see how to seed the relations between them.
        Thanks again

  8. Carlo

    Can you maybe make a simple projects for beginners.

  9. Tarik

    Thank you very much for sharing this great project.
    I installed the extension and create a new project and every thing is fine, but when i run the project as https://localhost:41112/swagger
    it show this error “This site can’t be reached”
    Did i missed some thing.
    Again thank you very much

      • Abhi

        Hello Mukeshbhai,

        I have used setup your application.
        While running as Kestrel it getting exception without any details error.

        The webpage at https://localhost:9001/
        might be temporarily down or it may have moved permanently to a new web address.

        Can you suggest to find real error logs behind this error?

        Thanks and regards

        • Mukesh Murugan

          Hi, as mentioned earlier, Kindly change the port settings of your WebAPI Application. This error usually occurs with a misconfigured IIS / Kestrel and used Ports. Try to change your ports from WebApi -> Properties -> launchsettings.json. Here change both application URL and SSL Port . That should fix it.


          • Mohd Rashid Siddique

            Hello Mukesh,

            I changed the application URL and SSL port. Also I switched to Kestrel to run the application. Still, I am getting This site can’t be reached error.

  10. shrikant chavan

    Thank You, Mukesh, Just install extension – it’s working fine, Can you add 1 more entity like Product Category and return the product list with category name.

    • Mukesh Murugan

      Hi, Sure, I will add that in the next release. But i guess it should be pretty straightforward to achieve it.

  11. Tarik

    It works when i switch it to Kestrel.
    Thank you very much.

  12. shrikant

    Hi Mukesh, I just trying to consume Authenticate API. But the response comes correctly. but when I try to get in the AuthenticationResponse DTO class. that time data come to null. I think something is required on following line

    var returnUser = JsonConvert.DeserializeObject(responseBody);

    Can you please help – where I am wrong.

    Full code:-
    public async Task ValidateUser()
    HttpClient = new HttpClient();
    string serializedUser = JsonConvert.SerializeObject(user);
    HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
    httpRequestMessage.Method = new HttpMethod(“POST”);
    httpRequestMessage.RequestUri = new Uri(“https://localhost:9001/api/Account/authenticate”);
    httpRequestMessage.Content = new StringContent(serializedUser);
    = new System.Net.Http.Headers.MediaTypeHeaderValue(“application/json”);

    // var response=await HttpClient.SendAsync(httpRequestMessage);
    HttpResponseMessage response = HttpClient.SendAsync(httpRequestMessage).Result;
    var responseStatusCode = response.StatusCode;
    var responseBody = response.Content.ReadAsStringAsync().Result;
    // AuthenticationResponse authenticationResponse = new AuthenticationResponse();
    if (responseStatusCode.ToString()==”OK”)

    var returnUser = JsonConvert.DeserializeObject(responseBody);

    await SessionStorage.SetItemAsync(“email”, user.Email);
    //await SessionStorage.SetItemAsync(“token”, authenticationResponse.JWToken);


    “succeeded”: true,
    “message”: “Authenticated“,
    “errors”: null,
    “data”: {
    “id”: “4f3cbcea-fcfc-42c0-940a-0e26f0323301”,
    “userName”: “”,
    “email”: “”,
    “roles”: [
    “isVerified”: true,
    “jwToken”: “xxxx”

    • Mukesh Murugan

      Hi, I do not understand it clearly. You tried to consume to authenticate endpoint and got the required response? I see the response looks fine too..

    • Mukesh Murugan

      Can i know if you getting the required response on both ‘returnUser’ and ‘responseBody’ objects?

  13. Thomas Bazan

    Hi Mikesh, awesome work. Learned a lot by using your code, since I am a beginner in C#.

    Shouldn’t there be a parameter in the PagedResponse that tells, how many pages the response has? Otherwise it will be hard to implement a client.


  14. Jimmy Chen

    Hi Mukesh, thanks a lot for the hard work. I’m also just a beginner in C# that’s been learning by going through your code. I’m currently trying to deploy this to Heroku with ClearDB mySql but I also wanted to be able to keep using local sql server with microsoft management studio so I tried changing the usesqlserver code to usemysql using pomelo as a provider if there was a database url environment variable and parsing my ClearDB database url to connection string to use it. However, when I auto generate migrations after deploying to Heroku using exec commands in webapi.csproj with dotnet ef update database –context ApplicationDbContext and IdentityContext, it tells me that there is wrong SQL syntax. Generating it locally after deleting migrations folder also still has sql server in it. Is there a nice and clean way to do this or completely move to mysql to use remote db?

  15. Johan

    Hi, thank you for this. Is it correct to assume that the WebApi project can also be replaced with a normal MVC project?

  16. Guru_Sharp

    Wondering will v2 be out soon?

    • Mukesh Murugan

      Yes, I am planning. But do not have much of other features in the TODO list. Do you have any other suggestions. In a month or so , I am thinking to build another similar project but with AdminLTE + IS4 + MVC/Razor + Hangfire. Any Suggestion? Thanks

  17. Miguel Larios

    Do yo have any sample with a Web Project using Razor Pages and comsumig any Web API

  18. Muhammad ElHelaly


  19. Jayr

    Hi, thanks for sharing, is there I need to config. call ILogger.loginformation(“error”) doesn’t log in file and console.

    • Mukesh Murugan

      Hi, We are using Serilog for Logging. If you see the appsettings, I have by default configured only to log on to the console (Kestrel web Server Console.)
      If you want to log it to additional targets like File, DB, please configure as needed.
      I have a complete tutorial of Serilog here –


      • Jayr

        In Email service;
        public ILogger _logger { get; }

        public EmailService(IOptions mailSettings,ILogger logger)
        _mailSettings = mailSettings.Value;
        _logger = logger;
        _logger.LogInformation(“Test log”);

        “Test log” doesn’t display in console or in file.

        • Mukesh Murugan

          Hi, the usage of ILogger is incorrect. It’s always ILogger. In your case it should be ILogger . Just try it and let me know.

          • Jayr

            I’ve finally made it work, by removing Log.CloseAndFlush(); in Program.cs. Is this proper?

  20. Anurag Gupta

    Hi Mukesh, Thanks for this great architecture. I noticed that due to the routing & versioning done from BaseApiController, developer cannot change the controller name in the route from the actual controller level.

    Is there any way of doing so? Or I need to remove the BaseApiController to implement this?

    For example, I want the UserProfileController to be called as “/api/v1/user-profile/” rather than being called as “/api/v1/UserProfile”.

    If possible, please respond asap. 🙂

    • Mukesh Murugan

      Hi, I had placed it in the BaseAPI Controller because you don’t have to worry about it everytime you create a new API. Yes, alternatively you can remove the inheritance from BaseAPIController and switch back to the default ControllerBase for your new APIs. This way you can have your own custom routes.


  21. abhi

    How to handle API response if user token expired ( unauthorised )?

    If token expired then how it would handle? currently it throwing below error message.

    Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: ‘System.DateTime’, Current time: ‘System.DateTime’.
    at Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
    at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
    at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
    at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
    at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()

    Share your thought.
    Thank you.

  22. Marcus Dungan

    Hello Mukesh, Thanks for the great article and extension. Is there an example of authorizing an endpoint based on the user roles. Also would the future updates include refresh token endpoint ?

    • Mukesh Murugan

      Refresh tokens are already included in the application partly. But yeah, it will be included in the upcoming update for sure. About your first question, authorizing based on user role is pretty straight forward. Just have a [Authorize(Roles=”SuperAdmin”)] attribute over the required controller / action method.


  23. Shiv nath

    Thanks in advance,
    Hi Mukesh Can you tell how i use ApplicationUser entity id property under Infrastructure.Identity in Core.Domain enitty

  24. Mubah

    Is this with Refresh Token

    • Mukesh Murugan

      Refresh tokens will be implemented in the upcoming version

  25. Antu

    Hello Mukesh,

    I learned a lot from this, thanks a lot.

    I do have a query, I have installed the template but I’m not sure what I should do in order to create a new table? I’ve gone through the simpler tutorial but whenever I hit update database command, the model isn’t getting generated in the database.


  26. Pham

    Hi Mukesh,

    I’m also just a beginner in C# so

    Do you have any sample Web Project using this API for Authentication ?

    Best regards

  27. Ajith Ramawickrama

    Hi Mukesh

    What is the best approach to handle SQL transactions with CQRS ?


Submit a Comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest