You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: aspnetcore/tutorials/first-web-api.md
+66-28Lines changed: 66 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ author: wadepickett
4
4
description: Learn how to build a web API with ASP.NET Core.
5
5
ms.author: wpickett
6
6
ms.custom: mvc, engagement-fy24
7
-
ms.date: 08/04/2024
7
+
ms.date: 02/13/2025
8
8
uid: tutorials/first-web-api
9
9
---
10
10
@@ -38,15 +38,15 @@ The following diagram shows the design of the app.
38
38
39
39
# [Visual Studio](#tab/visual-studio)
40
40
41
-
[!INCLUDE[](~/includes/net-prereqs-vs-8.0.md)]
41
+
[!INCLUDE[](~/includes/net-prereqs-vs-9.0.md)]
42
42
43
43
# [Visual Studio Code](#tab/visual-studio-code)
44
44
45
-
[!INCLUDE[](~/includes/net-prereqs-vsc-8.0.md)]
45
+
[!INCLUDE[](~/includes/net-prereqs-vsc-9.0.md)]
46
46
47
47
---
48
48
49
-
## Create a web project
49
+
## Create a Web API project
50
50
51
51
# [Visual Studio](#tab/visual-studio)
52
52
@@ -55,19 +55,25 @@ The following diagram shows the design of the app.
55
55
* Select the **ASP.NET Core Web API** template and select **Next**.
56
56
* In the **Configure your new project dialog**, name the project *TodoApi* and select **Next**.
57
57
* In the **Additional information** dialog:
58
-
* Confirm the **Framework** is **.NET 8.0 (Long Term Support)**.
59
-
* Confirm the checkbox for **Use controllers(uncheck to use minimal APIs)** is checked.
58
+
* Confirm the **Framework** is **.NET 9.0 (Standard Term Support)**.
60
59
* Confirm the checkbox for **Enable OpenAPI support** is checked.
60
+
* Confirm the checkbox for **Use controllers** is checked.
61
61
* Select **Create**.
62
62
63
-
## Add a NuGet package
63
+
## Add NuGet packages
64
64
65
-
A NuGet package must be added to support the database used in this tutorial.
65
+
This tutorial uses the following additional NuGet packages:
66
+
* `Microsoft.EntityFrameworkCore.InMemory`: Enables Entity Framework Core to work with an in-memory database rather than an external one, simplifying this tutorial.
67
+
* `Swashbuckle.AspNetCore.SwaggerUI`: Provides a user interface for exploring and testing API endpoints interactively through Swagger.
68
+
69
+
Add the following NuGet packages used in this tutorial.
66
70
67
71
* From the **Tools** menu, select **NuGet Package Manager > Manage NuGet Packages for Solution**.
68
72
* Select the **Browse** tab.
69
73
* Enter **Microsoft.EntityFrameworkCore.InMemory** in the search box, and then select `Microsoft.EntityFrameworkCore.InMemory`.
70
74
* Select the **Project** checkbox in the right pane and then select **Install**.
75
+
* Enter **Swashbuckle.AspNetCore.SwaggerUI** in the search box, and then select `Swashbuckle.AspNetCore.SwaggerUI`.
76
+
* Select the **Project** checkbox in the right pane and then select **Install**.
71
77
72
78
# [Visual Studio Code](#tab/visual-studio-code)
73
79
@@ -79,13 +85,16 @@ A NuGet package must be added to support the database used in this tutorial.
* Create a new web API project and open it in Visual Studio Code.
88
-
* Add a NuGet package that is needed for the next section.
95
+
* Adds NuGet packages that are used in this tutorial:
96
+
*`Microsoft.EntityFrameworkCore.InMemory`: Enables Entity Framework Core to work with an in-memory database so a real database won't be required for this tutorial.
97
+
*`Swashbuckle.AspNetCore.SwaggerUI`: Provides a user interface for exploring and testing API endpoints interactively through Swagger.
89
98
* Open the *TodoApi* folder in the current instance of Visual Studio Code.
@@ -94,17 +103,40 @@ A NuGet package must be added to support the database used in this tutorial.
94
103
95
104
[!INCLUDE[](~/includes/package-reference.md)]
96
105
97
-
### Test the project
106
+
### Test the Project
107
+
108
+
The project template:
109
+
110
+
* Creates a `WeatherForecast` API using controllers.
111
+
* Adds the `Microsoft.AspNetCore.OpenApi` package for OpenAPI support as a reference in the project file **TodoApi.csproj**.
112
+
* Adds OpenAPI services in **Project.cs** to automatically generate OpenAPI JSON documentation for the `WeatherForecast` API.
113
+
114
+
You can access the OpenAPI JSON documentation for the `WeatherForecast` API while the project is running by navigating your browser to `https://localhost:<port>/openapi/v1.json`, where `<port>` is a randomly chosen port number set during project creation.
98
115
99
-
The project template creates a `WeatherForecast` API with support for [Swagger](xref:tutorials/web-api-help-pages-using-swagger).
116
+
#### Configure the Swagger UI endpoint for the OpenAPI documentation
117
+
118
+
To configure [Swagger](xref:tutorials/web-api-help-pages-using-swagger) UI for testing the API, add the following highlighted code to the `Program.cs` file in the **TodoAPI** project:
* Adds the Swagger UI as a service to the app with `app.UseSwaggerUI()`.
125
+
* Sets the `SwaggerEndpoint()` option to the location of the OpenAPI documentation for this project.
126
+
* Ensures the Swagger UI is only available in the app development environment to limit information disclosure and security vulnerability.
100
127
101
128
# [Visual Studio](#tab/visual-studio)
102
129
103
130
Press Ctrl+F5 to run without the debugger.
104
131
105
132
[!INCLUDE[](~/includes/trustCertVS.md)]
106
133
107
-
Visual Studio launches the default browser and navigates to `https://localhost:<port>/swagger/index.html`, where `<port>` is a randomly chosen port number set at the project creation.
134
+
Visual Studio output pane shows messages similar to the following, indicating that the app is running and awaiting requests:
135
+
136
+
```output
137
+
Microsoft.Hosting.Lifetime: Information: Now listening on: https://localhost:{port number}
138
+
Microsoft.Hosting.Lifetime: Information: Now listening on: http://localhost:5071{port number}
139
+
```
108
140
109
141
# [Visual Studio Code](#tab/visual-studio-code)
110
142
@@ -123,19 +155,25 @@ Run the app:
123
155
```output
124
156
...
125
157
info: Microsoft.Hosting.Lifetime[14]
126
-
Now listening on: https://localhost:{port}
158
+
Now listening on: https://localhost:{port number}
127
159
...
128
160
```
129
161
130
162
* <kbd>Ctrl</kbd>+*click* the HTTPS URL in the output to test the web app in a browser.
131
163
132
-
* The default browser is launched to `https://localhost:<port>/swagger/index.html`, where `<port>` is the randomly chosen port number displayed in the output. There's no endpoint at `https://localhost:<port>`, so the browser returns [HTTP 404 Not Found](https://developer.mozilla.org/docs/Web/HTTP/Status/404). Append `/swagger` to the URL, `https://localhost:<port>/swagger`.
133
-
134
164
After testing the web app in the following instruction, press <kbd>Ctrl</kbd>+<kbd>C</kbd> in the integrated terminal to shut it down.
135
165
136
166
---
137
167
138
-
The Swagger page `/swagger/index.html` is displayed. Select **GET** > **Try it out** > **Execute**. The page displays:
168
+
#### View the Swagger UI
169
+
170
+
* Navigate a browser to `https://localhost:<port>/swagger/index.html`, where `<port>` is a randomly chosen port number set in **Properties/launchSettings.json** and displayed in the output.
171
+
172
+
The Swagger page `/swagger/index.html` is displayed.
173
+
174
+
* Select **GET** > **Try it out** > **Execute**.
175
+
176
+
The page displays:
139
177
140
178
* The [Curl](https://curl.haxx.se/) command to test the WeatherForecast API.
141
179
* The URL to test the WeatherForecast API.
@@ -144,8 +182,6 @@ The Swagger page `/swagger/index.html` is displayed. Select **GET** > **Try it o
144
182
145
183
If the Swagger page doesn't appear, see [this GitHub issue](https://github.com/dotnet/AspNetCore.Docs/issues/21647).
146
184
147
-
Swagger is used to generate useful documentation and help pages for web APIs. This tutorial uses Swagger to test the app. For more information on Swagger, see <xref:tutorials/web-api-help-pages-using-swagger>.
148
-
149
185
Copy and paste the **Request URL** in the browser: `https://localhost:<port>/weatherforecast`
150
186
151
187
JSON similar to the following example is returned:
@@ -232,13 +268,13 @@ In ASP.NET Core, services such as the DB context must be registered with the [de
232
268
233
269
Update `Program.cs` with the following highlighted code:
* Specifies that the database context will use an in-memory database.
277
+
* Specifies that the database context uses an in-memory database.
242
278
243
279
## Scaffold a controller
244
280
@@ -312,7 +348,7 @@ When the `[action]` token isn't in the route template, the [action](xref:mvc/con
312
348
313
349
## Update the PostTodoItem create method
314
350
315
-
Update the return statement in the `PostTodoItem` to use the [nameof](/dotnet/csharp/language-reference/operators/nameof) operator:
351
+
In **Controllers/TodoItemsController.cs** update the return statement in the `PostTodoItem` to use the [nameof](/dotnet/csharp/language-reference/operators/nameof) operator:
* Replace `[controller]` with the name of the controller, which by convention is the controller class name minus the "Controller" suffix. For this sample, the controller class name is **TodoItems**Controller, so the controller name is "TodoItems". ASP.NET Core [routing](xref:mvc/controllers/routing) is case insensitive.
381
-
* If the `[HttpGet]` attribute has a route template (for example, `[HttpGet("products")]`), append that to the path. This sample doesn't use a template. For more information, see [Attribute routing with Http[Verb] attributes](xref:mvc/controllers/routing#verb).
417
+
418
+
This sample doesn't use a route template with the [HttpGet] attribute. However in applications where an `[HttpGet]` attribute has a route template (for example, `[HttpGet("products")]`), append that to the path. For more information, see [Attribute routing with Http[Verb] attributes](xref:mvc/controllers/routing#verb).
382
419
383
420
In the following `GetTodoItem` method, `"{id}"` is a placeholder variable for the unique identifier of the to-do item. When `GetTodoItem` is invoked, the value of `"{id}"` in the URL is provided to the method in its `id` parameter.
384
421
@@ -397,7 +434,7 @@ The return type of the `GetTodoItems` and `GetTodoItem` methods is [ActionResult
`PutTodoItem` is similar to `PostTodoItem`, except it uses `HTTP PUT`. The response is [204 (No Content)](https://www.rfc-editor.org/rfc/rfc9110#status.204). According to the HTTP specification, a `PUT` request requires the client to send the entire updated entity, not just the changes. To support partial updates, use [HTTP PATCH](xref:Microsoft.AspNetCore.Mvc.HttpPatchAttribute).
403
440
@@ -447,19 +484,19 @@ A DTO may be used to:
447
484
448
485
To demonstrate the DTO approach, update the `TodoItem` class to include a secret field:
0 commit comments