finish lecture 2, edit lecture 1

main
borb 4 weeks ago
parent 2569099a51
commit 2a3191e4e9

File diff suppressed because one or more lines are too long

@ -11,7 +11,9 @@ title: 1. Introduction to ASP.NET
<!-- headingDivider: 5 -->
<!-- class: invert -->
## ASP.NET
## Getting started with ASP.NET
### ASP.NET
* ASP.NET is a server-side framework developed by Microsoft
* Introduced in 2002
@ -22,7 +24,7 @@ title: 1. Introduction to ASP.NET
* Web APIs
* Backend for desktop & mobile apps
## ASP.NET Core
### ASP.NET Core
* *__ASP.NET Core__* is a complete redesign & rewrite of ASP.NET
* Introduced in 2016
@ -36,7 +38,7 @@ title: 1. Introduction to ASP.NET
Xamarin for mobile
Use of NuGet packages add modularity and decrease the minimum memory footprint of your projects -->
### Why use ASP.NET Core?
#### Why use ASP.NET Core?
* As a .NET application, supports *__NuGet packages__* that can be added to your projects modularly
* Full support for C#
@ -49,7 +51,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
* .NET is constantly getting updates and new releases
* Learn to read [the documentation](https://learn.microsoft.com/en-us/aspnet/core/?view=aspnetcore-9.0)!
## Swagger & Swagger UI
### Swagger & Swagger UI
<div class='columns32' markdown='1'>
<div markdown='1'>
@ -68,7 +70,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
</div>
</div>
## Exercise 1: Creating an ASP.NET Core Web Application
### Exercise 1: Creating an ASP.NET Core Web Application
<!--_class: "exercise invert" -->
1) Open Visual Studio and from the right select *Create a new project*
@ -121,7 +123,6 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
![](imgs/2-aspnet-core-basics_4_1.png)
---
<!--_class: "exercise invert" -->
@ -189,7 +190,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
</div>
## ASP.NET Core Web API contents
### ASP.NET Core Web API contents
* In the previous exercise, we chose an API template for our new project, which have some files and dependencies already added
* The weather forecasts come from `WeatherForecastController.cs` in the *Controllers* folder
@ -197,7 +198,9 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
* Throughout this training, the aim is to get an understanding of the underlying logic of ASP.NET Core
* You can use the API template for the assignments, though
## `Program.cs`
## The heart of the server: `Program.cs`
### A default server program
* The `Program.cs` file in ASP.NET 7 is where the ***services*** for the web application are configured and the ***middleware*** is defined
* The file starts with defining the builder for the web application
@ -238,7 +241,9 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
app.Run();
```
## Routing
## An example controller: `WeatherController.cs`
### Routing and endpoints
* *__Routing__* is how web APIs match the requested URI to a corresponding action
* The URIs that can be used to get a response from the API are called the *__endpoints__* of the API
@ -249,30 +254,27 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
| `GET` | `http://someserver.com/api/products/3` | `GetProduct(int id)` |
| `POST` | `http://someserver.com/api/products` | `PostProduct()` |
## Attributes
### Attributes
* ***Attributes*** ([see C# Basics: Lecture 15](/education/csharp-basics/src/branch/main/15-design-patterns-in-csharp.md#attributes)) are a way of attaching metadata to entities (classes, methods, properties, etc.)
* In ASP.NET, attributes have a strong role in *__routing__*:
```csharp
[ApiController] // Attribute routing requirement,
// automatic HTTP 400 response, and more
[Route("[controller]")] // HTTP GET requests are routed to this method
[Route("[controller]")] // URIs with "/weatherforecast" are routed to this class
public class WeatherForecastController : ControllerBase
{
//...
}
// ...
[HttpGet] // URIs with "/weatherforecast" are routed to this class
[HttpGet] // HTTP GET requests are routed to this method
public IEnumerable<WeatherForecast> Get()
{
//...
}
}
```
## Attribute Routing
### Attribute Routing
| | Attribute | Request |
|:------------------|:-------------------------------------------------|:---------------------------------------------|
@ -281,9 +283,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
| Class:<br>Method: | `[Route("api")]`<br>`[HttpGet("products/{id}")]` | `GET <localhost>/api/products/12` |
| Class:<br>Method: | `[Route("api")]`<br>`[HttpPost("products")]` | `POST <localhost>/api/products` |
## Exercise 2: Setting up Routes
### Exercise 2: Setting up Routes
<!--_class: "exercise invert" -->
1) Change the routes in `WeatherForecastController.cs` so that the forecast result is printed at
@ -293,7 +293,7 @@ instead of
You can see the route change in the Swagger UI `GET` method.
## Handling HttpGet Requests
### Handling `HttpGet` Requests
* We have now established how to call methods with HTTP requests
* Additional parameters can be passed to the method with the URI:
@ -354,7 +354,7 @@ You can see the route change in the Swagger UI `GET` method.
</div>
## Exercise 3: Returning Your Own List
### Exercise 3: Returning Your Own List
<!--_class: "exercise invert" -->
1) Change the `GET` method so that instead of returning an `IEnumerable` of `WeatherForecast` objects, it returns a `List` of `string` objects.
@ -362,7 +362,9 @@ You can see the route change in the Swagger UI `GET` method.
2) Create a new method routed at `http://localhost:<port>/api/numberlist/k`, where `k` is any integer. The method should return an array of integers from `1` to `k`.
* For example, `http://localhost:<port>/api/numberlist/5` would return `[1,2,3,4,5]`. Test with browser (Swagger UI).
## Postman
## Sending requests with Postman
### Postman
* HTTP `POST` requests cannot be made with the browser's address bar, only `GET`!
* In websites, `POST` requests are usually made with forms
@ -376,14 +378,14 @@ You can see the route change in the Swagger UI `GET` method.
</div>
## Benefits of using Postman
### Benefits of using Postman
* When developing APIs, tools like Postman will almost always surface in the development cycle
* Postman lets you create configured HTTP requests to APIs, and save them to a JSON file
* This is great for testing your APIs without having to write code just for that purpose
* Supports all the necessary HTTP requests, like `GET`, `POST`, `PUT` and `DELETE`
## Exercise 4. Creating requests with Postman
### Exercise 4. Creating requests with Postman
<!--_class: "exercise invert" -->
Run the Weather API program, and test both methods with Postman.

File diff suppressed because one or more lines are too long

@ -3,25 +3,45 @@ marp: true
paginate: true
math: mathjax
theme: buutti
title: 2. HTTP Responses
title: 2. Controllers and HTTP Responses
---
# HTTP Responses
# Controllers and HTTP responses
<!-- headingDivider: 5 -->
<!-- class: invert -->
## ASP.NET Status Codes
## Controller-based API
* For a primer on HTTP status codes, check [Frontend basics: Lecture 2](https://gitea.buutti.com/education/frontend-basics/src/branch/main/2-http.md#http-status-codes)
* In the [previous Lecture 1](1-aspnet-introduction#an-example-controller-weathercontrollercs), we created a rudimentary ***controller-based web API*** in ASP.NET
* See also [Create web APIs with ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-9.0)
* ***Note:*** It's also possible to create [minimal APIs](https://learn.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-9.0&tabs=visual-studio) without controllers in ASP.NET
* Let's delve deeper into controllers that return HTTP responses with specific ***HTTP status codes***
* For a primer on HTTP status codes, check [Frontend basics: Lecture 2](https://gitea.buutti.com/education/frontend-basics/src/branch/main/2-http.md#http-status-codes)
* There are multiple possible status codes for each action
* The `ControllerBase` the controllers should inherit from includes *__result methods__* for creating `ActionResult` objects
### Controllers
* Controllers are classes that derive from the [`ControllerBase`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase?view=aspnetcore-9.0) class
* In the project template, we had this controller:
```csharp
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
```
* `ControllerBase` provides many properties and methods for handling HTTP requests
* Inside the class, we can create methods that correspond to different endpoints (see [Lecture 1: Routing and endpoints](1-aspnet-introduction#routing-and-endpoints))
* These are called *__result methods__*
### Result methods
* Result methods return `ActionResult` objects
* For example, a `CreatedAtAction` returns the 201 status code
* All `ActionResult` objects implement the `IActionResult` interface
* Includes at least a status code, and can contain data such as view items or an error message
* This result is processed into a response to then sent to client
* This result is processed into a response to then sent to client
* There are multiple possible status codes for each action (See the following table)
### Result methods
#### Some result methods
| Status Code | Result Method | Usage |
|:-------------------|:-----------------|:----------------------------|
@ -32,8 +52,7 @@ title: 2. HTTP Responses
| `404 - Not found` | `NotFound()` | `All actions` |
| `Custom` | `StatusCode()` | `All actions` |
### Status code example
#### Result methods: An example
```csharp
[HttpGet("{id}")]
@ -48,6 +67,7 @@ public IActionResult GetContactById(int id)
return Ok(contact);
}
```
---
* The previous code first attempts to find a `Contacts` object using the ID provided in the URI parameter

Loading…
Cancel
Save