ASP Net Core
Introduction
What is [Link] Core
A cross-platform, open-source application framework that you can use to
build dynamic web applications
You can build
server-rendered web applications,
backend server applications,
HTTP APIs
What types of applications can you build
Minimal APIs
Simple HTTP APIs that can be consumed by mobile applications or
browser-based single-page applications
Web APIs
An alternative approach to building HTTP APIs that adds more structure
and features than minimal APIs
What types of applications can you build
gRPC APIs
Used to build efficient binary APIs for server-to-server communication
using the gRPC protocol
Razor Pages
Used to build page-based server-rendered applications
What types of applications can you build
MVC controllers
Similar to Razor Pages. Model-View-Controller (MVC) controller
applications are for server-based applications but without the page-based
paradigm
Blazor WebAssembly
A browser-based single-page application framework that uses the
WebAssembly standard, similar to JavaScript frameworks such as Angular,
React, and Vue
What types of applications can you build
Blazor Server
Used to build stateful applications, rendered on the server, that send UI
events and page updates over WebSockets to provide the feel of a
client-side single-page application, but with the ease of development of a
server rendered application
What is [Link] Core
How an [Link] Core application processes a request
Overview of an [Link] Core application
Creating [Link] Core application
Getting an application up and running locally typically involves four basic steps
Generate:
Create the base application from a template to get started
Restore:
Restore all the packages and dependencies to the local project folder
using NuGet
Creating [Link] Core application
Getting an application up and running locally typically involves four basic steps
Build:
Compile the application, and generate all the necessary artifacts
Run:
Run the compiled application
Creating [Link] Core application
Visual Studio and the .NET CLI include many [Link] Core templates for
building different types of applications
NuGet packages and the .NET CLI
One of the foundational components of .NET cross-platform development is
the .NET CLI, which provides several basic commands for creating, building,
and running .NET applications
NuGet packages and the .NET CLI
The most common commands used during development are
● dotnet restore
● dotnet build
● dotnet run
NuGet packages and the .NET CLI
Understanding ASP Net Core project layout
The .csproj project file
The .csproj file is the project file for .NET applications and contains the details
required for the .NET tooling to build your project
It defines the type of project being built (web app, console app, or library),
which platform the project targets (.NET Core 10, .NET 10 and so on), and
which NuGet packages the project depends on
[Link] file
Defines your application
WebApplicationBuilder
Configures a lot of things by default
Configuration
Your app loads values from JSON files and environment variables that you
can use to control the app’s runtime behavior, such as loading connection
strings for a database
WebApplicationBuilder
Configures a lot of things by default
Logging
[Link] Core includes an extensible logging system for observability and
debugging
WebApplicationBuilder
Configures a lot of things by default
Services
Any classes that your application depends on for providing functionality
both those used by the framework and those specific to your application
must be registered so that they can be instantiated correctly at runtime
The WebApplicationBuilder configures the minimal set of services needed
for an [Link] Core app
WebApplicationBuilder
Configures a lot of things by default
Hosting
[Link] Core uses the Kestrel web server by default to handle requests
WebApplicationBuilder
The WebApplicationBuilder builds an IWebHostEnvironment object and
sets it on the Environment property
WebApplicationBuilder
IWebHostEnvironment exposes several environment-related properties,
such as
ContentRootPath—Location of the working directory for the app,
typically the folder in which the application is running
WebRootPath—Location of the wwwroot folder that contains static files
EnvironmentName—Whether the current environment is a development
or production environment
WebApplication instance
After registering your services with the IoC container on
WebApplicationBuilder and doing any further customization, you create a
WebApplication instance
WebApplication instance
You can do three main things with the WebApplication instance
Add middleware to the pipeline
Map endpoints that generate a response for a request
Run the application by calling Run()
Middleware
These small components execute in sequence when the application receives
an HTTP request
They can perform functions, such as logging, identifying the current user for a
request, serving static files, and handling errors
Endpoints
Endpoints define how the response should be generated for a specific request
to a URL in your app
Steps to create a typical [Link] Core app
Create a WebApplicationBuilder instance
Register the required services and configuration with the
WebApplicationBuilder
Call Build() on the builder instance to create a WebApplication instance
Add middleware to the WebApplication to create a pipeline
Map the endpoints in your application
Call Run() on the WebApplication to start the server and handle requests
Calling the /person endpoint
An overview of a request
to the /person URL
Handling requests with the middleware pipeline
In [Link] Core, middleware is a C# class that can handle an HTTP request or
response
Handling requests with the middleware pipeline
Middleware can
Handle an incoming HTTP request by generating an HTTP response
Process an incoming HTTP request, modify it, and pass it on to another
piece of middleware
Process an outgoing HTTP response, modify it, and pass it on to another
piece of middleware or to the [Link] Core web server
Handling requests with the middleware pipeline
The most important piece of middleware in most [Link] Core applications is
the EndpointMiddleware class
This class normally generates all your HTML and JavaScript Object Notation
(JSON) responses
Handling requests with the middleware pipeline
One of the most common use cases for middleware is for the cross-cutting
concerns of your application, including
Logging each request
Adding standard security headers to the response
Associating a request with the relevant user
Setting the language for the current request
Middleware Example
Middleware Example
Handling static files
Basic middleware pipeline for a minimal APIs application
Handling requests with the middleware pipeline
Note the following points about Middleware
Middleware is added with Use*() methods
WebApplication automatically adds some middleware to the pipeline,
such as the EndpointMiddleware
The order of the Use*() method calls is important and defines the order
of the middleware pipeline
Handling requests with the middleware pipeline
WebApplication automatically adds some or all of the following middleware
to the start of the middleware pipeline
HostFilteringMiddleware, ForwardedHeadersMiddleware,
DeveloperExceptionPageMiddleware, RoutingMiddleware,
AuthenticationMiddleware, AuthorizationMiddleware, and
EndpointMiddleware
Handling errors using middleware
If an exception occurs in a middleware component, it propagates up the
pipeline
If the exception isn’t caught by middleware earlier in the pipeline, a 500
“Server error” status code is sent to the user’s browser
Defining minimal API endpoints
Parameterized routes
Mapping verbs to endpoints
Mapping verbs to endpoints
Defining route handlers with functions
Check the next two slides
Generating responses with IResult
The endpoint middleware handles each return type as follows
void or Task
The endpoint returns a 200 response with no body
string or Task<string>
The endpoint returns a 200 response with the string serialized to
the body as text/plain
Generating responses with IResult
The endpoint middleware handles each return type as follows
IResult or Task<IResult>
The endpoint executes the [Link] method.
T or Task<T>
All other types (such as POCO objects) are serialized to JSON and
returned in the body of a 200 response as application/json
Returning status codes with Results and TypedResults
You can use these helpers to create a response with common status codes,
optionally including a JSON body
Each of the methods on Results and TypedResults returns an
implementation of IResult, which the endpoint middleware executes to
generate the final response
The difference is that the Results methods return an IResult, whereas
TypedResults return a concrete generic type, such as Ok<T>
Writing the response manually using HttpResponse
Results and TypedResults include methods for all the common status code
results you could need, but if you don’t want to use them for some reason,
you can always set the status code yourself directly on the HttpResponse
Writing the response manually using HttpResponse
Returning useful errors with Problem Details
Problem Details is a web specification
([Link] for providing
machine-readable errors for HTTP APIs
Returning useful errors with Problem Details
[Link] Core includes two helper methods for generating Problem Details
responses from minimal APIs:
[Link]() and
[Link]() (plus their TypedResults
counterparts)
Both of these methods return Problem Details JSON
The only difference is that Problem() defaults to a 500 status code, whereas
ValidationProblem() defaults to a 400 status and requires you to pass in a
Dictionary of validation errors
Returning useful errors with Problem Details
The ProblemHttpResult returned by these methods takes care of including
the correct title and description based on the status code, and generates the
appropriate JSON
You can override the default title and description by passing additional
arguments to the Problem() and ValidationProblem() methods
Converting all your responses to Problem Details
You can configure the ExceptionHandlerMiddleware (and
DeveloperExceptionPageMiddleware) to convert an exception to a
Problem Details response automatically
You can add the new IProblemDetailsService to your app by calling
AddProblemDetails() on WebApplicationBuilder Services
When the ExceptionHandlerMiddleware is configured without an
error-handling path, it automatically uses the IProblemDetailsService to
generate the response
Returning other data types
The Results and TypedResults also include helpers for other common
scenarios, such as returning a file or binary data
Returning other data types
[Link]()
Pass in the path of the file to return, and [Link] Core takes care of
streaming it to the client
[Link]()
For returning binary data, you can pass this method a byte[] to return
[Link]()
You can send data to the client asynchronously by using a Stream
Returning other data types
In each of [Link](), [Link]() and [Link]()
you can provide a content type for the data, and a filename to be used by the
client
The File and Byte methods even support range requests by specifying
enableRangeProcessing as true
Running common code with endpoint filters
It’s common to perform various cross-cutting activities for every endpoint
such as validation, logging, authorization, and auditing
Example validation code is shown in the following slide
[Link] Core includes endpoint filters feature in minimal APIs for running
these cross-cutting concerns
Running common code with endpoint filters
The next slide shows example endpoint filter usage
Adding multiple filters to an endpoint
If you need many endpoint-specific operations, you might consider using
multiple endpoint filters
Generalizing your endpoint filters
How to create generalized versions of filters that work with multiple endpoint
handlers
Filters or middleware: Which should you choose?
The endpoint filter pipeline is similar to the middleware pipeline in many ways
There are three main differences between middleware and filters
Middleware can run for all requests; filters will run only for requests that
reach the EndpointMiddleware and execute the associated endpoint
Filters or middleware: Which should you choose?
The endpoint filter pipeline is similar to the middleware pipeline in many ways
There are three main differences between middleware and filters
Filters have access to additional details about the endpoint that will
execute, such as the return value of the endpoint, for example an IResult
Middleware in general won’t see these intermediate steps, so it sees only
the generated response
Filters or middleware: Which should you choose?
The endpoint filter pipeline is similar to the middleware pipeline in many ways
There are three main differences between middleware and filters
Filters can easily be restricted to a subset of requests, such as a single
endpoint or a group of endpoints
Middleware generally applies to all requests
Organizing your APIs with route groups
All route duplication in the following example can be removed by using route
groups
Organizing your APIs with route groups
You can even create nested groups by calling MapGroup() on a group
The prefixes are applied to your endpoints in order, so the first MapGroup()
call defines the prefix used at the start of the route
[Link]("/fruit").MapGroup("/citrus")
for example, would have the prefix "/fruit/citrus"