* a framework for building internet connected applications, like
* ASP.NET is a server-side framework developed by Microsoft
* Introduced in 2002
* Successor to Microsoft's Active Server Pages (ASP) technology
* Runs on the .NET platform, and can use all .NET supported programming languages
* A framework for building Internet-connected applications, like
* Web apps
* Web APIs
* Backend for desktop & mobile apps
* rebuilt from ground up, NOT an update for the old ASP.NET
* open source, cross platform
* __ASP__ .NET Core supports the use of __NuGet packages__ , which can be added to your projects modularly
* In this course, we will be focusing on web APIs and won't be covering the front end development tools of ASP.NET
---
APIs are interfaces that applicaitons use to communicate with each other
## ASP.NET Core
* *__ASP.NET Core__* is a complete redesign & rewrite of ASP.NET
* Introduced in 2016
* Initially ran on both versions of .NET (Framework and Core)
* .NET Framework support was eventually dropped
* Open source, cross-platform
* Enhanced security compared to ASP.NET
* We will be focusing on Web APIs and won't be covering the frontend development tools of ASP.NET
<!-- 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
Use of NuGet packages add modularity and decrease the minimum memory footprint of your projects -->
# ASP.NET Core (continued)
### Why use ASP.NET Core?
* As a .NET application, supports *__NuGet packages__* that can be added to your projects modularly
* Full support for C#
* Base Class Library
* Great community support
@ -40,303 +47,369 @@ Use of NuGet packages add modularity and decrease the minimum memory footprint o
* Some companies have a long history with Microsoft frameworks
* ASP.NET is the logical choice in that case
* .NET is constantly getting updates and new releases
* Learning to read documentations is key
---
BCL includes all the things you have learned so far
* Learn to read [the documentation](https://learn.microsoft.com/en-us/aspnet/core/?view=aspnetcore-9.0)!
__Swagger & Swagger UI__
## Swagger & Swagger UI

<divclass='columns32'markdown='1'>
<divmarkdown='1'>
Swagger/OpenAPI: Language-independent specification for describing REST APIs without needing to look at the source code
* [Swagger](https://swagger.io/) (now [OpenAPI](https://swagger.io/docs/specification/v3_0/about/)) is a language-independent specification for describing REST APIs without needing to look at the source code
* [Swagger UI](https://swagger.io/tools/swagger-ui/): Web-based UI for automatically providing information about the API (actions and their capabilities) using the specification above
* The default implementation of Swagger UI in ASP.NET is called [Swashbuckle](https://github.com/domaindrivendev/Swashbuckle.AspNetCore) (see [docs](https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-7.0
))
* Useful for basic debugging and testing
Swagger UI: Web-based UI for automatically providing information about the API (actions and their capabilities) using the specification above
</div>
<divmarkdown='1'>
The default implementation of Swagger UI in ASP.NET is called [Swashbuckle](https://github.com/domaindrivendev/Swashbuckle.AspNetCore)

Useful for basic debugging and testing
</div>
</div>
---
## Exercise 1: Creating an ASP.NET Core Web Application
1) Open Visual Studio and from the right select *Create a new project*
2) Search for *ASP.NET* and select _ASP.NET Core Web API_***(NOTE: Not Web App!)***
# Exercise 1: Creating an ASP.NET Core Web Application
<divclass='columns12'markdown='1'>
<divmarkdown='1'>
Open Visual Studio and from the right select "Create a new project"

Search for _ASP.NET_ and select _ASP.NET Core Web API_
</div>
<divmarkdown='1'>


</div>
</div>
---
Configure for HTTPS would give the project the add secure authenticationThis would be for sensitive data
<!--_class: "exercise invert" -->
# Creating an ASP.NET Core Web Application (continued)
3) 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.
4) Select *.NET 9.0* under *Framework*. *Authentication type* should be *None* for now. Uncheck *Configure for HTTPS*. Click *Create* in the bottom right corner.
Give a name and click "Next" in the bottom right corner. Select .NET 7.0 under "Framework". Authentication type should be "None" for now. Uncheck "Configure for HTTPS" and click "Create" in the bottom right corner.
<divclass='columns'markdown='1'>
<divmarkdown='1'>

* ***Note:*** *Configure for HTTPS* would enforce HTTPS for added security (see [docs](https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-9.0&tabs=visual-studio%2Clinux-sles))

---
</div>
<divmarkdown='1'>
Configure for HTTPS would give the project the add secure authenticationThis would be for sensitive data

The new project is now created. Start debugging from the top (the play button with the text "http").
</div>
</div>

---
Configure for HTTPS would give the project the add secure authenticationThis would be for sensitive data
<!--_class: "exercise invert" -->
A web page should open, showing SwaggerUI for a weather forecast API. Click it open and select "Try it out". Execute the GET request and see what it returns.
Configure for HTTPS would give the project the add secure authenticationThis would be for sensitive data
<!--_class: "exercise invert" -->
# Creating an ASP.NET Core Web Application
6) Make sure `Program.cs` includes the following lines:
```csharp
builder.Services.AddControllers();
Close the window. Browse through the source files on Solution Explorer on the right and check where the weather forecasts come from.
builder.Services.AddEndpointsApiExplorer(); // add this
builder.Services.AddSwaggerGen(); // add this

// ...
---
if (app.Environment.IsDevelopment())
{
app.UseSwagger(); // add this
app.UseSwaggerUI(); // add this
app.MapOpenApi();
}
```
Configure for HTTPS would give the project the add secure authenticationThis would be for sensitive data
---
# ASP.NET Core Web API
<!--_class: "exercise invert" -->
In the previous exercise, we chose an API template for our new project, which have some files and dependencies already added
7) Start debugging from the top (the ▶ button with the text *http*).
* Click OK to trust the sertificates.
The weather forecasts come from "WeatherForecastController.cs" in the "Controllers" folder (more on Controllers later)

Throughout this course, the aim is to get an understanding of the underlying logic of ASP.NET Core
8) Open the Swagger UI in a web browser by going to `http://localhost:<port>/swagger`.
* The port number is shown on the debug console window that should now be open.

You can use the API template for the assignments, though
---
# Program.cs
<!--_class: "exercise invert" -->
The Program.cs file in ASP.NET 7 is the file where the services for the web application are configured and middleware is defined
9) A web page should open, showing SwaggerUI for a weather forecast API. Click it open 🔽.
10) Click *Try it out*, and 11. *Execute* the **GET** request and see what it returns.
The file starts with defining the builder for the web application
<divclass='columns'markdown='1'>
<divmarkdown='1'>
var builder = WebApplication.CreateBuilder(args);

The program is actually a console application, which also hosts a web server
</div>
<divmarkdown='1'>
By default, ASP.NET applications use Kestrel and IIS as a server: [https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-7.0](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-7.0)


# Services
</div>
</div>
* The controllers and some other components (like Swagger) are added to the application as services
* Services are components that are available anywhere within your program via dependency injection (more on that [later in the course](https://docs.google.com/presentation/u/0/d/1vDSvwMafnibrc8ZfQXlKFAm2m--3b-aUUAxQUGzTBf0/edit) )
* As the comment right above it suggests, more can be added as needed
---
This will make more sense after we start adding own services
<!--_class: "exercise invert" -->
# Configuring Middleware
12) Close the window. Browse through the source files on Solution Explorer on the right and check where the weather forecasts come from.
Handling of each HTTP request is defined as a set of middlewares
<divclass='centered'>
Middleware is software that's assembled into an app pipeline to handle requests and responses

They can decide whether to pass the request into the next middleware, or modify the data/request as needed.
</div>
if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthorization(); app.MapControllers(); app.Run();
## ASP.NET Core Web API contents
# Routing
* 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
* (More on Controllers later...)
* 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
__Routing __ is how web APIs match the requested URI to a corresponding action
## `Program.cs`
The URI:s that can be used to get a response from the API are called the __endpoints __ of the API
* 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
```csharp
var builder = WebApplication.CreateBuilder(args);
```
* The program is actually a console application that also hosts a web server
* The default server in ASP.NET applications is [Kestrel](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore-9.0) (lightweight, cross-platform)
* The old default is [IIS](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-9.0) (Windows-specific, nowadays used as a [reverse proxy](https://en.wikipedia.org/wiki/Reverse_proxy) server)
* The controllers and some other components (like Swagger) are added to the application as ***services***
* Services are components that are available anywhere within your program via *dependency injection* (introduced in [C# Basics Lecture 15](https://gitea.buutti.com/education/csharp-basics/src/branch/main/15-design-patterns-in-csharp.md))
Attributes are a way of attaching metadata with code (classes, methods, properties, etc.)
```csharp
// Add services to the container.
In ASP.NET, attributes have a strong role in __routing__ :
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
```
* As the comment above suggests, more services can be added as needed
[ApiController]
### Middlewares
[Route("[controller]")]
* Handling of each HTTP request is defined as a set of [middlewares](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-9.0)
* Middleware is a software that's added into the middle of an app pipeline to handle requests and responses
* Middleware can decide whether to modify the data/request as needed, and pass the request into the next middleware
```csharp
if (app.Environment.IsDevelopment()){
app.UseSwagger();
app.UseSwaggerUI();
app.MapOpenApi();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
```
public class WeatherForecastController : ControllerBase
## Routing
{
* *__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
* ***Attributes*** ([see C# Basics: Lecture 15](/:root/education/csharp-basics/15-design-patterns-in-csharp#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
public class WeatherForecastController : ControllerBase
{
//...
}
// ...
[HttpGet] // URIs with "/weatherforecast" are routed to this class
Change the Get method so that instead of returning an IEnumerable of WeatherForecast objects, it returns a List of string objects. Fill the list with e.g. names and make it as long as you want. Test with browser (Swagger UI).
</div>
Create a new method, which is routed at http://localhost:xxxxx/api/numberlist/k, where _k_ is any integer. The method should return an array of integers from 1 to _k_ . For example: http://localhost:xxxxx/api/numberlist/5 would return [1,2,3,4,5]. Test with browser (Swagger UI).
## Exercise 3: Returning Your Own List
<!--_class: "exercise invert" -->
# Postman
1) Change the `GET` method so that instead of returning an `IEnumerable` of `WeatherForecast` objects, it returns a `List` of `string` objects.
* Fill the list with e.g. names and make it as long as you want. Test with browser (Swagger UI).
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).
HTTP POST requests cannot be made with the browsers location bar
## Postman
In websites, POST requests are usually made with forms
* HTTP `POST` requests cannot be made with the browser's address bar, only `GET`!
* In websites, `POST` requests are usually made with forms
* In applications, all requests are sent by the client application
* For testing APIs, multiple tools like [Postman](https://www.postman.com/) or [Insomnia](https://insomnia.rest/) exist
* Before we cover handling `POST`, `PUT` and other requests in ASP.NET, let's first see how to make them with Postman
In applications, all requests are sent by the client application
<divclass='centered'>
For testing APIs, multiple tools like __Postman __ exist

Before we cover handling POST, PUT and other requests in ASP.NET, let's first see how to make them with Postman
</div>

## Benefits of using Postman
# Postman (continued)
* 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`
When developing APIs, Postman will almost always turn up in the development cycle
## Exercise 4. Creating requests with Postman
<!--_class: "exercise invert" -->
Postman lets you create configured HTTP requests to APIs
Run the Weather API program, and test both methods with Postman.
This is great for testing your APIs without having to write code just for that purpose
1) To get started, open Postman (You can sign in or skip the login)
* Close the opened window to go straight to making requests
Supports all the necessary HTTP requests, like GET, POST and DELETE
<divclass='centered'>
# Creating Requests with Postman

* To get started, open Postman
* You can sign in or skip the login
* Close the opened window to go straight to making requests
</div>

---
<!--_class: "exercise invert" -->
# Creating Requests with Postman (continued)
<divclass='columns23'markdown='1'>
<divmarkdown='1'>
Create your request by selecting the method and entering the URL
2) Create your request by selecting the method and entering the URL
3) The response with the content body and status code show up below!
The response with the content body and status code show up below
</div>
<divmarkdown='1'>

# Exercise 4: Trying out Postman
Run the program you have worked on in the previous lecture assignments. Test both methods with Postman.