Git Product home page Git Product logo

apiboilerplate's Introduction

ApiBoilerPlate.AspNetCore

Visual Studio Marketplace Version Visual Studio Marketplace Installs Nuget Nuget

A simple yet organized project template for building ASP.NET Core APIs using .NET Core 3.1 (the latest/fastest version of .NET Core to date) with preconfigured tools and frameworks. It features most of the functionalities that an API will have such as database CRUD operations, Token-based Authorization, Http Response format consistency, Global exception handling, Logging, Http Request rate limiting, HealthChecks and many more. The goal is to help you get up to speed when setting up the core structure of your app and its dependencies when spinning up a new ASP.NET Core API project. This enables you to focus on implementing business specific code requirements without you having to copy and paste the core structure of your project, common features, and installing its dependencies all over again. This will speed up your development time while enforcing standard project structure with its dependencies and configurations for all your apps.

If you are looking for a project template for ASP.NET Core API that you can reuse across your team, or if you are new to ASP.NET Core and would like to get up to speed on how it works without having you to configure most of the basic features that an API will have, then this is for you.

How To Get It?

There are two ways to install the template:

Tools and Frameworks Used

Keep in mind that you can always replace and choose whatever framework you want to use for your API. After all, the template is just a skeleton for your project structure with default preconfigured middlewares. For example, you can always replace Dapper with Entity Framework Core, PetaPoco, etc. and configure them yourself. You can also replace Serilog with whatever logging frameworks and providers you want that works with ASP.NET Core - the choice is yours.

Key Takeaways

Here's the list of the good stuff that you can get when using the template:

  • Configured Sample Code for database CRUD operations.
  • Configured Basic Data Access using Dapper.
  • Configured Logging using Serilog.
  • Configured AutoMapper for mapping entity models to DTOs.
  • Configured FluentValidation for DTO validations.
  • Configured AutoWrapper for handling request Exceptions and consistent HTTP response format.
  • Configured AutoWrapper.Server for unwrapping the Result attribute from AutoWrapper's ApiResponse output.
  • Configured Swagger API Documentation.
  • Configured CORS.
  • Configured JWT Authorization and Validation.
  • Configured Sample Code for Requesting Client Credentials Token.
  • Configured Swagger to secure API documentation with Bearer Authorization.
  • Configured Sample Code for connecting Protected External APIs.
  • Configured Sample Code for implementing custom API Pagination.
  • Configured HttpClient Resilience and Transient fault-handling.
  • Configured Http Request Rate Limiter.
  • Configured HealthChecks and HealthChecksUI.
  • Configured Unit Test Project with xUnit.
  • [Deprecated] Configured Sample Code for Worker service. For handling extensive process in the background, you may want to look at the Worker Template created by Jude Daryl Clarino. The template was also based on ApiBoilerPlate.

Install the Template from .NET CLI

  1. Install the latest .NET Core SDK.
  2. Run dotnet new -i apiboilerplate.aspnetcore. This will install the template in your machine.
  3. Run dotnet new apiboilerplate --name "MyAPI" -o samples. This will generate the project template named MyAPI within the samples directory.

Once installed, you should see the following console message:

The template "ASP.NET Core API Template for .NET Core 3.x" was created successfully.

Install the Template from Visual Studio Marketplace

Note: If you are using the previous version of the template, make sure to uninstall it first before you install the latest version.

  1. Fire up Visual Studio 2019, click Continue without code link.
  2. On the Extensions menu, click Manage Extensions.
  3. Click Online and then search for ApiBoilerPlate.
  4. Click Download. The extension is then scheduled for install.

To complete the installation, close all instances of Visual Studio.

Alternatively, you can download and install the VSIX Extension directly at the following link: https://marketplace.visualstudio.com/items?itemName=vmsdurano.ApiProjVSExt

Create a new Project from ApiBoilerPlate Extension

  1. Open Visual Studio 2019 and then select Create New Project box
  2. The newly installed template should appear at the top. You can also type "ApiBoilerPlate" in the search bar.
  3. Click the ApiBoilerPlate item and then click Next.
  4. Name your project to whatever you like and then click Create.
  5. Visual Studio should generate the files for you.

Steps to Run the Template

STEP 1: Create a Test local Database:

  1. Open Visual Studio 2019
  2. Go to View > SQL Server Object Explorer
  3. Drilldown to SQL Server > (localdb)\MSSQLLocalDB
  4. Right-click "Database" Folder
  5. Click "Add New Database"
  6. Name it as "TestDB" and click OK
  7. Right-click on the "TestDB" database and then select "New Query"
  8. Run the script below to generate the "Person" table.
CREATE TABLE [dbo].[Person]
(
	[Id] INT NOT NULL PRIMARY KEY IDENTITY(1,1), 
    	[FirstName] NVARCHAR(20) NOT NULL, 
    	[LastName] NVARCHAR(20) NOT NULL, 
    	[DateOfBirth] DATETIME NOT NULL
)

STEP 2: Update Database ConnectionString (Optional)

If you follow step 1, then you can skip this step and run the application right away.

If you have a different database and table name then you need to change the connectionString in appsettings.json that is pointing to the newly created database. You can get the connectionString values in the properties window of the "TestDB" database in Visual Studio.

Walkthrough

Give a Star! โญ

Feel free to request an issue on github if you find bugs or request a new feature. Your valuable feedback is much appreciated to better improve this project. If you find this useful, please give it a star to show your support for this project.

Contributors

  • Vincent Maverick Durano - Blog
  • Jude Daryl Clarino - Blog
  • Bruno Renato Feliciano - LinkedIn

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Donate

If you find this project useful โ€” or just feeling generous, consider buying me a beer or a coffee. Cheers! ๐Ÿป โ˜•

BMC

Thank you!

apiboilerplate's People

Contributors

brunao05 avatar judedaryl avatar proudmonkey 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

apiboilerplate's Issues

Suggestion for new version

Some personal opinions after having used this template for a new API.

For the new version of this BoilerPlate I would suggest not including so much "extras", at least not extras that are enabled by default. While it might be useful, it has the side effect of turning this boilerplate template more into a code sample/tutorial than something you can use to get a quick start. This as you would have to spend about as much time trying to understand how those extras work as well as removing them if you don't use it, as it would take to configure a new API from scratch and configure health checks etc.

I think this might turn away potential users of this excellent template, that really offers a lot of value. Well, that's my personal opinions, others might disagree :)

Swagger authorization not working (401 error)

First, THANK YOU for creating and sharing the template.

Background: The ApiBoilerPlate was used to generate a WebAPI project. After adding [Authorize] attribute to the PersonsController, the endpoints require to Bearer JWT access token as expected. However, accessing any endpoint in the PersonsController will get 401.

Issue - Para authorization and bearer token are not included in the header upon submit in Swagger. External testing using Postman worked fine.

Fix - Made the following changes in Infrastructure\Installers\RegisterSwagger.cs

            options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Scheme = "Bearer",
                Description = "Enter 'Bearer' following by space and JWT.",
                Name = "Authorization",
                //Type = SecuritySchemeType.Http,
                Type = SecuritySchemeType.ApiKey,
                In = ParameterLocation.Header,
            });

See below for the code -
https://github.com/workcontrolgit/EmployeeProfileWebAPIDemo/blob/master/EmployeeProfile/EmployeeProfile/Infrastructure/Installers/RegisterSwagger.cs

I will fork and submit a pull request.

Usinng this with angular 2+

Hi, I would be grateful if you could show small sample on how to integrate this with an angular 2+ client application.

Thanks.

Runtime problem after updating AspNetCoreRateLimit to 4.0+ (with solution)

If you run into problems like this after updating AspNetCoreRateLimit (or have it updated for you by another NuGet package):

System.InvalidOperationException: Unable to resolve service for type 'AspNetCoreRateLimit.IProcessingStrategy' while attempting to activate 'AspNetCoreRateLimit.IpRateLimitMiddleware'.

This is the solution needed to get it working again:

        // See release notes for 4.0.0 https://github.com/stefanprodan/AspNetCoreRateLimit/releases
        services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();

In RegisterRequestRateLimiter class

HealthChecksUI not start

I start the project and try to open HealthChecksUI. I don't see the UI.

"HealthChecksUI": { "HealthChecks": [ { "Name": "HTTP-Api-Basic", "Uri": "https://localhost:5001/selfcheck" } ], "Webhooks": [ { "Name": "", "Uri": "", "Payload": "", "RestoredPayload": "" } ], "EvaluationTimeInSeconds": 10, "MinimumSecondsBetweenFailureNotifications": 60, "HealthCheckDatabaseConnectionString": "Data Source=Infrastructure\\HealthChecks\\Db\\healthchecksdb" }

ActionResult not used

Hi,

How come ActionResult / Task< ActionResult > isn't used in this project but instead more direct approaches like Task? Just curious if there is a special reason for it?

Why is Microsoft.Extensions.Logging used instead of Serilog?

I've noticed that even though SeriLog is used in the projects, the usings are:

using Microsoft.Extensions.Logging;

instead of:

using Serilog

so that stuff like:

_logger = logger?.ForContext()

won't work.

Of course, you can change this in your own code (or the entire code if you want to) but I guess there is a reason for it being as it is?

Main reason for asking this is because we want to add custom Override to serilog like:

  "Override": {
    "Microsoft": "Warning",
    "System": "Warning",
    "System.Net.Http.HttpClient": "Information",
    "OurClassHere": "Debug"

and was not able to figure out how to do it which led us to this.

Thanks.

When I run the project I get the error in browser (HTTP Error 500.24)

I have installed the template form extensions menu of visual studio and created a new project. I also created a table in my database and updated the connection string in appSettings.json file. when i run the project i see the following error in my browser as shown in the image.

HTTP Error 500.24 - Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Most likely causes:
system.web/identity@impersonate is set to true.

Things you can try:
If the application supports it, disable client impersonation.
If you are certain that it is OK to ignore this error, it can be disabled by setting system.webServer/validation@validateIntegratedModeConfiguration to false.

Capture asp netboilerplate error

.NET 6 ApiBoilerPlate

Vincent,
Happy New year 2022, I have same questions as others, is there a plan to update this to .NET 6 ?

Can we add support for JWT Auth scheme and related configuration with Authroization Role, Police, permisssion etc

Can we add support for JWT Auth scheme and related configuration with Authorization Role, Police, permission etc.

ApiBoilerPlate project template is very good and has lots of things which required for most projects.

As most of the project is using username and password and based on that they generate JWT Token.
However in provided sample it's using API key and secret which is only used for one client it can be used as daemon service As per my understanding.

For API Project most people are not using IdentityServer due to lots of complexity and configuration instead use custom or dotnetcore identity authentication with JWT scheme for API Project.

Add some detail on creating a service from the built API

Great effort! However, how do I create a Windows Service from the resultant exe file? Almost nowhere in the web that I can find, are there clear instructions for running a WebApi based on Net Core 3.1 as a Windows Service using either Kestrel or Http.Sys as the self host.
Our applications and WebAPIs have to be installed and run at our customers' sites and most tutorials and blogs that I can find provide little or no help with Publish and Deploy to third parties who may or may not have strong Devops skills. I have found some good ideas for changing the Program.cs to recognise if the app is running in debug mode or as a Windows Service, but these mostly apply to .Net Framework bases.
Can you add some information regarding this?

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.