From 2a3191e4e9ceeb0945e3e25196d6da90a499b0c8 Mon Sep 17 00:00:00 2001 From: borb Date: Wed, 9 Jul 2025 19:30:06 +0300 Subject: [PATCH] finish lecture 2, edit lecture 1 --- 1-aspnet-introduction-slides.html | 120 ++++++++++-------- 1-aspnet-introduction.md | 64 +++++----- ...controllers-and-http-responses-slides.html | 66 +++++++--- 2-controllers-and-http-responses.md | 40 ++++-- 4 files changed, 176 insertions(+), 114 deletions(-) rename 2-http-responses-slides.html => 2-controllers-and-http-responses-slides.html (77%) diff --git a/1-aspnet-introduction-slides.html b/1-aspnet-introduction-slides.html index 0d57db6..edc687e 100644 --- a/1-aspnet-introduction-slides.html +++ b/1-aspnet-introduction-slides.html @@ -13,11 +13,14 @@ /* buutti.css */ /* @theme buutti */div#\:\$p>svg>foreignObject>section .columns{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns12{display:grid;grid-template-columns:1fr 2fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns21{display:grid;grid-template-columns:2fr 1fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns32{display:grid;grid-template-columns:3fr 2fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns23{display:grid;grid-template-columns:2fr 3fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .columns111{display:grid;grid-template-columns:1fr 1fr 1fr;gap:calc(var(--marpit-root-font-size, 1rem) * 1)}div#\:\$p>svg>foreignObject>section .centered{display:flex;flex-direction:column;justify-content:center;text-align:center}div#\:\$p>svg>foreignObject>section .tableborderless td,div#\:\$p>svg>foreignObject>section th{border:none!important;border-collapse:collapse}div#\:\$p>svg>foreignObject>section.extra{background-color:#5d275d;background-image:linear-gradient(to bottom,#401a40,#1d0c1d);color:white}div#\:\$p>svg>foreignObject>section.extra a{color:rgb(145,255,209)}div#\:\$p>svg>foreignObject>section.exercise{background-color:#29366f;background-image:linear-gradient(to bottom,#20636a,#173742);color:white}div#\:\$p>svg>foreignObject>section.exercise a{color:rgb(211,173,255)} -/* @theme 8lh3rjev3cpwiqc307miuofc8u1wrc5dagzppz442 */div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]{columns:initial!important;display:block!important;padding:0!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:before,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:before{display:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]{all:initial;display:flex;flex-direction:row;height:100%;overflow:hidden;width:100%}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container][data-marpit-advanced-background-direction=vertical]{flex-direction:column}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split]>div[data-marpit-advanced-background-container]{width:var(--marpit-advanced-background-split,50%)}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split=right]>div[data-marpit-advanced-background-container]{margin-left:calc(100% - var(--marpit-advanced-background-split, 50%))}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure{all:initial;background-position:center;background-repeat:no-repeat;background-size:cover;flex:auto;margin:0}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure>figcaption{position:absolute;border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;white-space:nowrap;width:1px}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content],div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo]{background:transparent!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo],div#\:\$p>svg[data-marpit-svg]>foreignObject[data-marpit-advanced-background=pseudo]{pointer-events:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background-split]{width:100%;height:100%}
+/* @theme zk24th0mt1mugosj50ud5w3iz0lt31kd4zssn5haex6 */div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]{columns:initial!important;display:block!important;padding:0!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:before,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:before{display:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]{all:initial;display:flex;flex-direction:row;height:100%;overflow:hidden;width:100%}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container][data-marpit-advanced-background-direction=vertical]{flex-direction:column}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split]>div[data-marpit-advanced-background-container]{width:var(--marpit-advanced-background-split,50%)}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split=right]>div[data-marpit-advanced-background-container]{margin-left:calc(100% - var(--marpit-advanced-background-split, 50%))}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure{all:initial;background-position:center;background-repeat:no-repeat;background-size:cover;flex:auto;margin:0}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure>figcaption{position:absolute;border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;white-space:nowrap;width:1px}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content],div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo]{background:transparent!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo],div#\:\$p>svg[data-marpit-svg]>foreignObject[data-marpit-advanced-background=pseudo]{pointer-events:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background-split]{width:100%;height:100%}

Introduction to ASP.NET

-
-

ASP.NET

+
+

Getting started with ASP.NET

+
+
+

ASP.NET

  • ASP.NET is a server-side framework developed by Microsoft
  • Introduced in 2002
  • @@ -32,8 +35,8 @@
-
-

ASP.NET Core

+
+

ASP.NET Core

  • ASP.NET Core is a complete redesign & rewrite of ASP.NET
      @@ -47,8 +50,8 @@
    • We will be focusing on Web APIs and won't be covering the frontend development tools of ASP.NET
-
-

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# @@ -74,8 +77,8 @@
-
-

Swagger & Swagger UI

+
+

Swagger & Swagger UI

    @@ -90,8 +93,8 @@
-
-

Exercise 1: Creating an ASP.NET Core Web Application

+
+

Exercise 1: Creating an ASP.NET Core Web Application

  1. Open Visual Studio and from the right select Create a new project
  2. @@ -106,7 +109,7 @@
-
+
  1. Give a Project name and set a Location for the repository, and check Place solution and project in the same directory. Click Next in the bottom right corner.
  2. Select .NET 9.0 under Framework. Authentication type should be None for now. Uncheck Configure for HTTPS. Click Create in the bottom right corner.
  3. @@ -123,7 +126,7 @@
-
+
  1. Add Swagger to your project. Go to View > Other Windows > Package Manager Console and run the following command:
    Install-Package Swashbuckle.AspNetCore -Version 6.6.2
     
    @@ -131,7 +134,7 @@

-
+
  1. Make sure Program.cs includes the following lines:
    builder.Services.AddControllers();
     
    @@ -150,7 +153,7 @@ builder.Services.AddSwaggerGen();           // add th
     
-
+
  1. Start debugging from the top (the ▶ button with the text http).
      @@ -168,7 +171,7 @@ builder.Services.AddSwaggerGen(); // add th
-
+
  1. A web page should open, showing SwaggerUI for a weather forecast API. Click it open 🔽.
  2. Click Try it out, and 11. Execute the GET request and see what it returns.
  3. @@ -183,7 +186,7 @@ builder.Services.AddSwaggerGen(); // add th
-
+
  1. Close the window. Browse through the source files on Solution Explorer on the right and check where the weather forecasts come from.
@@ -191,8 +194,8 @@ builder.Services.AddSwaggerGen(); // add th

-
-

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 @@ -204,8 +207,11 @@ builder.Services.AddSwaggerGen(); // add th
  • 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
    var builder = WebApplication.CreateBuilder(args);
    @@ -219,7 +225,7 @@ builder.Services.AddSwaggerGen();           // add th
     
-
+

Services

  • @@ -239,7 +245,7 @@ builder.Services.AddSwaggerGen();
-
+

Middlewares

  • Handling of each HTTP request is defined as a set of middlewares
  • @@ -256,8 +262,11 @@ 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
  • @@ -289,29 +298,29 @@ app.Run();
-
-

Attributes

+
+

Attributes

  • Attributes (see C# Basics: Lecture 15) are a way of attaching metadata to entities (classes, methods, properties, etc.)
  • -
  • In ASP.NET, attributes have a strong role in routing:
    [ApiController]   // Attribute routing requirement,
    -                  // automatic HTTP 400 response, and more
    -[Route("[controller]")] // HTTP GET requests are routed to this method
    +
  • In ASP.NET, attributes have a strong role in routing:
    [ApiController]           // Attribute routing requirement,
    +                          // automatic HTTP 400 response, and more
    +
    +[Route("[controller]")]   // URIs with "/weatherforecast" are routed to this class
     public class WeatherForecastController : ControllerBase
     {
       //...
    -}
    -// ...
    -[HttpGet] // URIs with "/weatherforecast" are routed to this class
    -public IEnumerable<WeatherForecast> Get()
    -{
    -  //...
    +  [HttpGet]               // HTTP GET requests are routed to this method
    +  public IEnumerable<WeatherForecast> Get()
    +  {
    +    //...
    +  }
     }
     
-
-

Attribute Routing

+
+

Attribute Routing

@@ -344,8 +353,8 @@ app.Run();
-
-

Exercise 2: Setting up Routes

+
+

Exercise 2: Setting up Routes

  1. Change the routes in WeatherForecastController.cs so that the forecast result is printed at
    @@ -355,8 +364,8 @@ 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:
    [Route("api")]
    @@ -376,7 +385,7 @@ instead of

-
+
  • The URI parameters can be made optional with '?'
  • A default value must be then set for the method parameter:
    [Route("api")]
    @@ -396,7 +405,7 @@ instead of

-
+
  • Apply constraints for the parameters by setting them after :
  • If the URI doesn't fit the constraints, the response will hold a 404 status code
    [HttpGet("products/{id:int}")]              // Required type: int
    @@ -408,8 +417,8 @@ instead of

-
-

Exercise 3: Returning Your Own List

+
+

Exercise 3: Returning Your Own List

  1. Change the GET method so that instead of returning an IEnumerable of WeatherForecast objects, it returns a List of string objects. @@ -424,8 +433,11 @@ instead of
-
-

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
  • @@ -437,8 +449,8 @@ instead of

-
-

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
  • @@ -446,8 +458,8 @@ instead of
  • Supports all the necessary HTTP requests, like GET, POST, PUT and DELETE
-
-

Exercise 4. Creating requests with Postman

+
+

Exercise 4. Creating requests with Postman

Run the Weather API program, and test both methods with Postman.

    @@ -461,7 +473,7 @@ instead of

-
+
  1. Create your request by selecting the method and entering the URL
  2. @@ -473,7 +485,7 @@ instead of

APIs are interfaces that applicaitons use to communicate with each other +

APIs are interfaces that applicaitons use to communicate with each other Xamarin for mobile Use of NuGet packages add modularity and decrease the minimum memory footprint of your projects

\ No newline at end of file diff --git a/1-aspnet-introduction.md b/1-aspnet-introduction.md index 7835fff..9735e14 100644 --- a/1-aspnet-introduction.md +++ b/1-aspnet-introduction.md @@ -11,7 +11,9 @@ title: 1. Introduction to ASP.NET -## 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
@@ -68,7 +70,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
-## Exercise 1: Creating an ASP.NET Core Web Application +### Exercise 1: Creating an ASP.NET Core Web Application 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) - --- @@ -189,7 +190,7 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o -## 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 + [ApiController] // Attribute routing requirement, + // automatic HTTP 400 response, and more + + [Route("[controller]")] // URIs with "/weatherforecast" are routed to this class public class WeatherForecastController : ControllerBase { //... - } - // ... - [HttpGet] // URIs with "/weatherforecast" are routed to this class - public IEnumerable Get() - { - //... + [HttpGet] // HTTP GET requests are routed to this method + public IEnumerable 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:
Method: | `[Route("api")]`
`[HttpGet("products/{id}")]` | `GET /api/products/12` | | Class:
Method: | `[Route("api")]`
`[HttpPost("products")]` | `POST /api/products` | - - -## Exercise 2: Setting up Routes +### Exercise 2: Setting up Routes 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. -## Exercise 3: Returning Your Own List +### Exercise 3: Returning Your Own List 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:/api/numberlist/k`, where `k` is any integer. The method should return an array of integers from `1` to `k`. * For example, `http://localhost:/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. -## 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 Run the Weather API program, and test both methods with Postman. diff --git a/2-http-responses-slides.html b/2-controllers-and-http-responses-slides.html similarity index 77% rename from 2-http-responses-slides.html rename to 2-controllers-and-http-responses-slides.html index ba6c943..218645b 100644 --- a/2-http-responses-slides.html +++ b/2-controllers-and-http-responses-slides.html @@ -1,4 +1,4 @@ -2. HTTP Responses
-

HTTP Responses

+/* @theme m17a7k329lvqvpxhz904l7jlr2gqbubxt9vl339b9ga */div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]{columns:initial!important;display:block!important;padding:0!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]:before,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:after,div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content]:before{display:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]{all:initial;display:flex;flex-direction:row;height:100%;overflow:hidden;width:100%}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container][data-marpit-advanced-background-direction=vertical]{flex-direction:column}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split]>div[data-marpit-advanced-background-container]{width:var(--marpit-advanced-background-split,50%)}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background][data-marpit-advanced-background-split=right]>div[data-marpit-advanced-background-container]{margin-left:calc(100% - var(--marpit-advanced-background-split, 50%))}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure{all:initial;background-position:center;background-repeat:no-repeat;background-size:cover;flex:auto;margin:0}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=background]>div[data-marpit-advanced-background-container]>figure>figcaption{position:absolute;border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;white-space:nowrap;width:1px}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=content],div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo]{background:transparent!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background=pseudo],div#\:\$p>svg[data-marpit-svg]>foreignObject[data-marpit-advanced-background=pseudo]{pointer-events:none!important}div#\:\$p>svg>foreignObject>section[data-marpit-advanced-background-split]{width:100%;height:100%}
+

Controllers and HTTP responses

-
-

ASP.NET Status Codes

+
+

Controller-based API

    -
  • -

    For a primer on HTTP status codes, check Frontend basics: Lecture 2

    +
  • In the previous Lecture 1, we created a rudimentary controller-based web API in ASP.NET +
  • -
  • -

    There are multiple possible status codes for each action

    +
  • Let's delve deeper into controllers that return HTTP responses with specific HTTP status codes +
  • -
  • -

    The ControllerBase the controllers should inherit from includes result methods for creating ActionResult objects

    +
+
+
+

Controllers

    -
  • 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
  • +
  • Controllers are classes that derive from the ControllerBase class
  • +
  • In the project template, we had this controller:
    [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) +
      +
    • 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
  • +
  • There are multiple possible status codes for each action (See the following table)
  • +
+
+
+

Some result methods

@@ -79,8 +107,8 @@
-
-

Status code example

+
+

Result methods: An example

[HttpGet("{id}")]
 public IActionResult GetContactById(int id)
 {
@@ -94,7 +122,7 @@
 }
 
-
+
  • The previous code first attempts to find a Contacts object using the ID provided in the URI parameter
      @@ -106,7 +134,7 @@
-
+

Exercise 1: Returning status codes

    diff --git a/2-controllers-and-http-responses.md b/2-controllers-and-http-responses.md index 6a74c45..7a14fc1 100644 --- a/2-controllers-and-http-responses.md +++ b/2-controllers-and-http-responses.md @@ -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 -## 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