0% found this document useful (0 votes)
21 views37 pages

CH 2

Uploaded by

kbeydoun1980
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views37 pages

CH 2

Uploaded by

kbeydoun1980
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

ASP.

Net Core – Your


first application
Kamal Beydoun
Lebanese University – Faculty of Sciences I
[email protected]
A brief overview of an ASP.NET Core
application
• The HttpContext constructed by the
ASP.NET Core web server is used by the
application as a sort of storage box for a
single request.
• the subsequent response can be
associated with it and stored in it.
• It includes properties of the request,
request-specific services, data that’s
been loaded, or errors that have
occurred.
• The web server fills the initial HttpContext
with details of the original HTTP request and
other configuration details and passes it on to
2
the rest of the application.
A brief overview of an ASP.NET Core
application
 Kestrel is responsible for receiving the
request data and constructing a C#
representation of the request, but it doesn’t
attempt to handle the request directly.

 Kestrel hands the HttpContext to the


middleware pipeline found in every
ASP.NET Core application.

3
A brief overview of an ASP.NET Core
application
 MVC block: responsible for generating the HTML
that makes up the pages of a typical ASP.NET
Core web app.

 most of the business logic of your app

 Not every app needs an MVC block, but it’s


typically how you’ll build most apps that
display HTML to a user.

4
Creating your first ASP.NET Core
application
1. Generate—Create the base application from a template to get started.
2. Restore—Restore all the packages and dependencies to the local project
folder using NuGet.
3. Build—Compile the application and generate all the necessary assets.
4. Run—Run the compiled application.

5
Create an App with VS
1. To create your first web application, open Visual Studio and perform the following steps:
2. Choose File > New > Project.
3. From the Templates node on the left, choose .NET Core, and then select ASP.NET Core Web
Application.
4. Enter a Name, Location, and a solution name (optional) and click OK
5. Select ASP.NET Core 6 .
6. The generated application will target ASP.NET Core 7.
7. Select Web Application (Model-View-Controller) for MVC applications or Razor pages for
Razor Applications.
6
Create an App with VS

7
Create an App with VS

8
Create an App with VS

using the .NET CLI :


dotnet new mvc –o WebApplication1

The -o argument ensures the


CLI creates the template in a
subfolder called
WebApplication1.

9
Create an App with VS

10
Building the application
Both Visual Studio and the .NET CLI automatically restore packages
when they first create your project
You can compile your application by choosing Build > Build Solution, by
using the shortcut Ctrl+Shift+B, or by running
dotnet build
from the command line.

11
.NET Core Command Line Interface (CLI)
 One of the foundational components of .NET Core cross-platform development
 The most common commands during development are
 dotnet restore
 dotnet build
 dotnet run
 Each of these commands should be run inside your project folder and will act on that project alone.
 dotnet restore, will ensure your application’s NuGet dependencies are copied to your project folder.
 You can compile your application using dotnet build.
 if there are no issues, will produce an output that can be run using dotnet run.

12
Understanding the project layout

13
csproj project file : project layout
It 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
3.1, .NET 5, and so on), and which NuGet packages the project
depends on.

14
The csproj project file: defining your
dependencies

15
The Program class: building a web host

Main uses a
IHostBuilder, created by
the call to
CreateDefaultBuilder, to
define how the IHost is
configured, before
instantiating the
IWebHost with a call to
Build().

16
Program Class vs Startup class

17
The Startup class: configuring your
application
The Startup class is responsible for configuring two main aspects of your
application:
Service registration—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 correctly instantiated at runtime.
 Middleware and endpoints—How your application handles and
responds to requests.
18
The Startup class: configuring your
application

19
The Startup class: configuring your
application
1. The IHostBuilder created in
Program calls ConfigureServices
and then Configure
2. Each call configures a different part
of your application, making it
available for subsequent method
calls.
3. Any services registered in the
ConfigureServices method are
available to the Configure method.
4. Once configuration is complete, an
IHost is created by calling Build()
on the IHostBuilder. 20
Adding and configuring services
 ASP.NET Core uses small, modular components for each distinct feature.
 exposed as one or more services that are used by the application.
 service refers to any class that provides functionality to an application
 service could be classes exposed by a library or code you’ve written for your application.
 The single responsibility principle (SRP) states that every class should be responsible
for only a single piece of functionality—it should only need to change if that required
functionality changes.
 You must register each service with the “container” before it can be used in your
application.
21
Adding and configuring services

As well as registering framework-related services,


this method is where you’d register any custom
services you have in your application.

 The IServiceCollection is a list of every known service that your application will need to use.
 By adding a new service to it, you ensure that whenever a class declares a dependency on your
service, the IoC container (dependency Injection) knows how to provide it.

22
23
Developer Exception Page
 DeveloperExceptionP
ageMiddleware
(added by the
UseDeveloperExceptio
nPage() call) will be
presented with as much
information as possible
in the browser

24
Default Exception Page

25
Https and Static File Middleware

• The next piece of middleware added to the


pipeline is the HttpsRedirectionMiddleware,
using the statement:
app.UseHttpsRedirection();
• This ensures your application only responds to
secure (HTTPS) requests and is an industry
best practice.

• Static file Middelware is responsible for


handling requests for static files such as CSS
files, JavaScript files, and images.
26
Generating responses with Razor Pages
• Normally, the final piece of middleware in a pipeline is the endpoint middleware
which works with the routing middleware to match a request URL’s path to a
configured route, which defines which Razor Page to invoke.
• Once a Razor Page has been selected, the routing middleware stores a note of the
selected Razor Page in the request’s HttpContext and continues executing the
middleware pipeline.
• Eventually the request will reach the endpoint middleware. The endpoint
middleware executes the Razor Page to generate the HTML response, and sends
it back to the browser.
27
Generating HTML with Razor Pages
• Razor Pages are stored in cshtml files within the Pages folder of your
project.

28
Generating HTML with Razor Pages

29
Handling request logic with PageModels and
handlers
• A page handler is a method
that runs in response to a
request.
• Razor Page models must be
derived from the PageModel
class.
• They can contain multiple
page handlers, though typically
they only contain one or two
30
Why page handlers ?
• The key thing to remember here is that you now have a framework for
performing arbitrarily complex functions in response to a request.
• You could easily update the handler method to load data from the database, send an
email, add a product to a basket, or create an invoice—all in response to a simple HTTP
request.
• This extensibility is where a lot of the power in Razor Pages (and the MVC
pattern in general) lies.
• The other important point is that you’ve separated the execution of these
methods from the generation of the HTML itself.
31
32
Summary
• The csproj file contains details of how to build your project, including
which NuGet
• packages it depends on. It’s used by Visual Studio and the .NET CLI to
build your application.
• Restoring the NuGet packages for an ASP.NET Core application
downloads all your project’s dependencies so it can be built and run.

33
Summary
• Program.cs defines the static void Main entry point for your application.
This
function is run when your app starts, the same as for console applications.
• Program.cs is where you build an IHost instance, using an IHostBuilder.
• The helper method, Host.CreateDefaultBuilder()creates an IHostBuilder
that loads configuration settings and sets up logging. Calling Build()
creates the IHost instance.

34
Summary
• The ConfigureWebHostDefaults extension method configures the generic host using a
WebHostBuilder.
• It configures the Kestrel HTTP server, adds IIS integration if necessary, and specifies
the application’s Startup class.
• You can start the web server and begin accepting HTTP requests by calling Run on the
IHost.
• Startup is responsible for service configuration and defining the middleware pipeline.
• All services, both framework and custom application services, must be registered in the
call to ConfigureServices in order to be accessed later in your application.
35
Summary
• Middleware is added to the application pipeline with IApplicationBuilder.
Middleware defines how your application responds to requests.
• The order in which middleware is registered defines the final order of the middleware
pipeline for the application. Typically, EndpointMiddleware is the last middleware in
the pipeline.
• Earlier middleware, such as StaticFileMiddleware, will attempt to handle the request
first. If the request is handled, EndpointMiddleware will never receive the request.
• Razor Pages are located in the Pages folder and are typically named according to the
URL path they handle. For example, Privacy.cshtml handles the path /Privacy.
36
Summary
• Razor Pages must contain the @page directive as the first line of the file.
• Page models derive from the PageModel base class and contain page handlers. Page handlers
are methods named using conventions that indicate the HTTP verb they handle.
• For example, OnGet handles the GET verb.
• Razor templates can contain standalone C#, standalone HTML, and dynamic HTML generated
from C# values. By combining all three, you can build highly dynamic applications.
• Razor layouts define common elements of a web page, such as headers and footers.
• They let you extract this code into a single file, so you don’t have to duplicate it across every
Razor template.

37

You might also like