Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Updates for minimalapi + scaffolding
Browse files Browse the repository at this point in the history
  • Loading branch information
jongalloway committed May 12, 2022
1 parent f7385c1 commit 639827d
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 28 deletions.
161 changes: 133 additions & 28 deletions docs/1. Create BackEnd API project.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,41 @@

## Creating a new project using Visual Studio

1. Create and add a new project named `BackEnd` and name the solution `ConferencePlanner` using File / New / ASP.NET Core Web API. Select the Web API template, No Auth, no Docker support.
1. Create and add a new project named `BackEnd` and name the solution `ConferencePlanner` using File / New / ASP.NET Core Web API. Select the Web API template, No Auth, no Docker support. Uncheck the box that says "Use controllers (uncheck to use minimal APIs)".

![Creating a new solution in Visual Studio](images/vs-new-project-api.png)
![Adding a project to the solution](images/vs-name-backend-project.png)
![Web API Project settings](images/vs-backend-additional-info.png)

> ***Note:* If not using Visual Studio, create the project using `dotnet new webapi` at the cmd line, details as follows:**
## Creating a new project from the command line

> 1. Create folder ConferencePlanner and call `dotnet new sln` at the cmd line to create a solution
> 2. Create sub-folder BackEnd and create a project using `dotnet new webapi` at the cmd line inside the folder BackEnd
> 3. Add the project to the solution using `dotnet sln add BackEnd/BackEnd.csproj`
If not using Visual Studio, create the project using the dotnet cli at the command line as follows:

1. Create folder ConferencePlanner and create a solution by running the following console command:

```bash
dotnet new sln
```

1. Create sub-folder BackEnd and create a project by running

```bash
dotnet new webapi -minimal
```

1. Add the project to the solution using the following command

```bash
dotnet sln add BackEnd/BackEnd.csproj
```

1. Open the solution in Visual Studio Code by running the following command:

```bash
code .
```

## Adding model classes

1. Add a new `Models` folder to the root of the application.
1. Add a new `Speaker` class using the following code:
Expand All @@ -37,8 +61,28 @@
}
```

1. Add a reference to the NuGet package `Microsoft.EntityFrameworkCore.Sqlite` version `6.0.1`.
> This can be done from the command line using `dotnet Backend/Backend.csproj add package Microsoft.EntityFrameworkCore.Sqlite --version 6.0.1`
## Add NuGet packages and EF Core tools

Before you start, you need to add the required packages.

### Adding packages using Visual Studio

1. In Visual Studio, right click the project and select `Manage NuGet Packages...`, then select `Browse...` and search for `Microsoft.EntityFrameworkCore.Sqlite` and click `Install`.

1. Search for `Microsoft.EntityFrameworkCore.Tools` and click `Install`.

### Adding packages from the command line

1. From the terminal, run the following command:

```bash
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
```

This command adds the NuGet package that contains the EF Core SQLite database provider and all its dependencies, including the common EF Core services.

## Adding a database context

1. Next we'll create a new Entity Framework DbContext. Create a new `ApplicationDbContext` class in the `Models` folder using the following code:

```csharp
Expand Down Expand Up @@ -78,7 +122,7 @@

## Register the DB Context Service

1. Add the top of `Program.cs` to read as follows:
1. Just below the top line of `Program.cs`, add the code read the connection string from the *appsettings.json* file and set up the Sqlite database, so that it reads as follows:

```csharp
var builder = WebApplication.CreateBuilder(args);
Expand All @@ -94,30 +138,36 @@
## Configuring EF Migrations

You will be using either a terminal window or the Visual Studio Package Manager Console for the following steps.
You will be using either a terminal window or the Visual Studio Developer PowerShell terminal for the following steps.

1. If you are using Visual Studio, open the Package Manager Console by selecting Tools -> NuGet Package Manager -> Package Manager Console and enter `cd BackEnd`.
1. If you are using Visual Studio, open the Developer PowerShell terminal by selecting View -> Terminal and enter `cd BackEnd`.

1. If you are using a terminal window, navigate to the project directory (the directory containing the `Program.cs` file).

1. Install the required NuGet package for migrations:

```bash
dotnet add package Microsoft.EntityFrameworkCore.Design --version 6.0.1
dotnet add package Microsoft.EntityFrameworkCore.Design
```

1. Install the EntityFramework global tool `dotnet-ef` using the following command:

```bash
dotnet tool install -g dotnet-ef --version 6.0.1
dotnet tool install -g dotnet-ef
```

1. If you receive a message that the tool is already installed, update to the newest version with the following command:

```bash
dotnet tool update -g dotnet-ef --version 6.0.1
dotnet tool update -g dotnet-ef
```

1. Build the project using the following command:

```bash
dotnet build
```

1. Run the following commands in the command prompt:

```bash
Expand All @@ -136,49 +186,104 @@ Commands Explained
>If your database ever gets in a bad state and you'd like to reset things, you can use `dotnet ef database drop` followed by `dotnet ef database update` to remove your database and run all migrations again.
## A quick look at the Weather Forecast Controller
## A quick look at the Weather Forecast API

Scroll down to the bottom of `Program.cs` and you'll see some sample code for the Weather Forecast API:

```csharp
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

First, open the `Controllers` folder and take a quick look at the `WeatherForecastController`. You'll see a simple function that corresponds to the HTTP GET verb. You'll see the output of this controller in a bit, but first we'll build our own API controller for the `Speakers` model class.
internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
```

## Scaffolding an API Controller
You'll see a simple API that returns weather forecasts and is mapped to the HTTP GET verb. You'll see the output of this API in a bit, but first we'll build our own API for the `Speakers` model class.

## Scaffolding the Speaker API

### Using Visual Studio

1. Right-click the `Controllers` folder and select Add/Controller. Select "API Controller with actions, using Entity Framework".
1. In the dialog, select the `Speaker` model for the Model Class, `ApplicationDbContext` for the "Data Context Class" and click the `Add` button.
![Scaffold SpeakersController in Visual Studio](images/scaffold-api-controller.png)
1. Right-click the Project and select *Add* / *New Scaffolded Item...*. Select "API with read/write endpoints, using Entity Framework" and click `Add`.
1. In the dialog, select the `Speaker` model for the Model Class.
1. Click the `+` button to add a new endpoint named `SpeakerEndpoints`.
1. Select `ApplicationDbContext` for the "Data Context Class" and click the `Add` button.
1. Check the `Enable Open API` checkbox and click the `Add` button.
![Scaffold SpeakersController in Visual Studio](images/scaffold-speaker-endpoint.png)

### Using the cmd line

1. Install the `aspnet-codegenerator` global tool by running the following command:

```bash
dotnet tool install -g dotnet-aspnet-codegenerator --version 6.0.1
dotnet tool install -g dotnet-aspnet-codegenerator
```

1. If you receive a message that the tool is already installed, update to the newest version with the following command:

```bash
dotnet tool update -g dotnet-aspnet-codegenerator --version 6.0.1
dotnet tool update -g dotnet-aspnet-codegenerator
```

> Note: You will need to close and reopen the console window to be able to use this tool.
> Note: You may need to close and reopen the console window to be able to use this tool.
1. Run the following command to view the help for the `minimalapi` scaffolding command:

```bash
dotnet aspnet-codegenerator minimalapi --help
```

1. Run the following in the project folder at the cmd line:

```bash
dotnet aspnet-codegenerator controller -api -name SpeakersController -m Speaker -dc BackEnd.Models.ApplicationDbContext -outDir Controllers
dotnet aspnet-codegenerator minimalapi -e SpeakerEndpoints -dc ApplicationDbContext -o -m BackEnd.Models.Speaker
```

## Testing the API using the Swashbuckle
This scaffolder does two things:

1. It generates an endpoints class named `SpeakersEndpoints` with API endpoints that map to database operations using the `ApplicationDbContext` class and the `Speaker` model.

1. It adds the follwing code to the `Program.cs` file to register the endpoints class:

```csharp
app.MapSpeakerEndpoints();
```

We'll make a quick improvement to add tags to the **SpeakerEndpoints** class so it works a little better with Open API.

1. Open the `SpeakersEndpoints.cs` file in the project folder.

1. Open the Quick Replace menu using **Edit** / **Find and Replace** / **Quick Replace**.

1. In the Find textbox, enter `.WithName(`

In this section, we'll be adding documentation to our API using the Swashbuckle NuGet package.
1. In the Replace textbox, enter `.WithTags("Speaker").WithName(`

[Swashbuckle.AspNetCore](https://github.com/domaindrivendev/swashbuckle.aspnetcore) is an open source project for generating Swagger documents for Web APIs that are built with ASP.NET Core. This package is included by default in ASP.NET Core Web API project in .NET 6.0.
1. Select **Replace All (Alt-A)**

[Swagger](https://swagger.io) is a machine readable representation of a RESTful API that enables support for interactive documentation, client SDK generation and discoverability.
## Testing the API using Swagger UI

Additional information on using Swashbuckle in ASP.NET Core is available in this tutorial: [ASP.NET Web API Help Pages using Swagger](https://docs.microsoft.com/aspnet/core/tutorials/web-api-help-pages-using-swagger)
In this section, we'll be interacting with the API using the [Swagger UI](https://swagger.io/tools/swagger-ui/) web interface. Swagger is a machine readable representation of a RESTful API that enables support for interactive documentation, client SDK generation and discoverability.

1. Run the application (F5 in Visual Studio or `dotnet run` from console).
1. If the browser does not automatically open, browse to the Swagger UI at `http://localhost:<random_port>/swagger`.
Expand Down
Binary file added docs/images/scaffold-speaker-endpoint.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/vs-backend-additional-info.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/vs-name-backend-project.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 639827d

Please sign in to comment.