Everything Flashcards

1
Q

Explain the Startup Class

A

The Startup class configures services and the app’s request pipeline.

ASP.NET Core apps use a Startup class, which is named Startup by convention. The Startup class:

Optionally includes a ConfigureServices method to configure the app’s services. A service is a reusable component that provides app functionality. Services are registered in ConfigureServices and consumed across the app via dependency injection (DI) or ApplicationServices.
The ConfigureServices method is:
Called by the host before the Configure method to configure the app’s services.
For features that require substantial setup, there are Add{Service} extension methods on IServiceCollection. For example, AddDbContext, AddDefaultIdentity, AddEntityFrameworkStores, and AddRazorPages:

Includes a Configure method to create the app’s request processing pipeline.

ConfigureServices and Configure are called by the ASP.NET Core runtime when the app starts.

The Startup class is specified when the app’s host is built. In Program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the configure method in startup do?

A

The Configure method is used to specify how the app responds to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance. IApplicationBuilder is available to the Configure method, but it isn’t registered in the service container. Hosting creates an IApplicationBuilder and passes it directly to Configure.

The ASP.NET Core templates configure the pipeline with support for:

Developer Exception Page
Exception handler
HTTP Strict Transport Security (HSTS)
HTTPS redirection
Static files
ASP.NET Core MVC and Razor Pages

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(“/Error”);
app.UseHsts();
}

    app. UseHttpsRedirection();
    app. UseStaticFiles();

    app. UseRouting();
    app. UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }

Each Use extension method adds one or more middleware components to the request pipeline. For instance, UseStaticFiles configures middleware to serve static files.

Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the chain, if appropriate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain layouts

A

Most web apps have a common layout that provides the user with a consistent experience as they navigate from page to page. The layout typically includes common user interface elements such as the app header, navigation or menu elements, and footer.

Common HTML structures such as scripts and stylesheets are also frequently used by many pages within an app. All of these shared elements may be defined in a layout file, which can then be referenced by any view used within the app. Layouts reduce duplicate code in views.

By convention, the default layout for an ASP.NET Core app is named _Layout.cshtml. The layout files for new ASP.NET Core projects created with the templates are:

Razor Pages: Pages/Shared/_Layout.cshtml

Controller with views: Views/Shared/_Layout.cshtml

The layout defines a top level template for views in the app. Apps don’t require a layout. Apps can define more than one layout, with different views specifying different layouts.

A layout can optionally reference one or more sections, by calling RenderSection. Sections provide a way to organize where certain page elements should be placed. Each call to RenderSection can specify whether that section is required or optional:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you specify a layout?

A

Razor views have a Layout property. Individual views specify a layout by setting this property:
@{
Layout = “_Layout”;
}
The layout specified can use a full path (for example, /Pages/Shared/_Layout.cshtml or /Views/Shared/_Layout.cshtml) or a partial name (example: _Layout). When a partial name is provided, the Razor view engine searches for the layout file using its standard discovery process. The folder where the handler method (or controller) exists is searched first, followed by the Shared folder. This discovery process is identical to the process used to discover partial views.

By default, every layout must call RenderBody. Wherever the call to RenderBody is placed, the contents of the view will be rendered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the _ViewStart.cshtml file do?

A

Code that needs to run before each view or page should be placed in the _ViewStart.cshtml file. By convention, the _ViewStart.cshtml file is located in the Pages (or Views) folder. The statements listed in _ViewStart.cshtml are run before every full view (not layouts, and not partial views).

Like ViewImports.cshtml, _ViewStart.cshtml is hierarchical. If a _ViewStart.cshtml file is defined in the view or pages folder, it will be run after the one defined in the root of the Pages (or Views) folder (if any).

The file can for example specify that all views will use the _Layout.cshtml layout.

_ViewStart.cshtml and _ViewImports.cshtml are not typically placed in the /Pages/Shared (or /Views/Shared) folder. The app-level versions of these files should be placed directly in the /Pages (or /Views) folder.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does _ViewImports.cshtml file do?

A

Views and pages can use Razor directives to import namespaces and use dependency injection. Directives shared by many views may be specified in a common _ViewImports.cshtml file. The _ViewImports file supports the following directives:

@addTagHelper
@removeTagHelper
@tagHelperPrefix
@using
@model
@inherits
@inject
The file doesn't support other Razor features, such as functions and section definitions.

A sample _ViewImports.cshtml file:
@using WebApplication1
@using WebApplication1.Models
@using WebApplication1.Models.AccountViewModels
@using WebApplication1.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The _ViewImports.cshtml file for an ASP.NET Core MVC app is typically placed in the Pages (or Views) folder. A _ViewImports.cshtml file can be placed within any folder, in which case it will only be applied to pages or views within that folder and its subfolders. _ViewImports files are processed starting at the root level and then for each folder leading up to the location of the page or view itself. _ViewImports settings specified at the root level may be overridden at the folder level.

For example, suppose:

The root level _ViewImports.cshtml file includes @model MyModel1 and @addTagHelper *, MyTagHelper1.
A subfolder _ViewImports.cshtml file includes @model MyModel2 and @addTagHelper *, MyTagHelper2.
Pages and views in the subfolder will have access to both Tag Helpers and the MyModel2 model.

If multiple _ViewImports.cshtml files are found in the file hierarchy, the combined behavior of the directives are:

@addTagHelper, @removeTagHelper: all run, in order
@tagHelperPrefix: the closest one to the view overrides any others
@model: the closest one to the view overrides any others
@inherits: the closest one to the view overrides any others
@using: all are included; duplicates are ignored
@inject: for each property, the closest one to the view overrides any others with the same property name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is routing?

A

Routing is registered in the middleware pipeline in Startup.Configure.

Example:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/", async context =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}); } Routing uses a pair of middleware, registered by UseRouting and UseEndpoints:

UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request.
UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.
The preceding example includes a single route to code endpoint using the MapGet method:

When an HTTP GET request is sent to the root URL /:
The request delegate shown executes.
Hello World! is written to the HTTP response. By default, the root URL / is https://localhost:5001/.
If the request method is not GET or the root URL is not /, no route matches and an HTTP 404 is returned.

Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app’s executable endpoints. Endpoints are the app’s units of executable request-handling code. Endpoints are defined in the app and configured when the app starts. The endpoint matching process can extract values from the request’s URL and provide those values for request processing. Using endpoint information from the app, routing is also able to generate URLs that map to endpoints.

Apps can configure routing using:

Controllers
Razor Pages
SignalR
gRPC Services
Endpoint-enabled middleware such as Health Checks.
Delegates and lambdas registered with routing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are Razor Pages?

A

Razor Pages are a simplified way of generating HTML responses.

Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views.
@page makes the file into an MVC action - which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .cshtml suffix.

Example:
@page

<h1>Hello, world!</h1>

<h2>The time on the server is @DateTime.Now</h2>

PAGEMODEL
A similar page, using a PageModel class, is shown in the following two files. The Pages/Index2.cshtml file:

@page
@using RazorPagesIntro.Pages
@model Index2Model

<h2>Separate page model</h2>

<p>
@Model.Message
</p>

The Pages/Index2.cshtml.cs page model:

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using System;

namespace RazorPagesIntro.Pages
{
    public class Index2Model : PageModel
    {
        public string Message { get; private set; } = "PageModel in C#";
        public void OnGet()
        {
            Message += $" Server time is { DateTime.Now }";
        }
    }
}

By convention, the PageModel class file has the same name as the Razor Page file with .cs appended. For example, the previous Razor Page is Pages/Index2.cshtml. The file containing the PageModel class is named Pages/Index2.cshtml.cs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why are razor pages useful?

A

The simplicity of Razor Pages means you can start getting results sooner than with the MVC Framework, which can require a relatively complex preparation process. Razor Pages are also easier for less experienced web developers to understand because the relationship between the code and content is more obvious.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How are razor pages used?

A

Razor Pages associate a single view with the class that provides it with features and uses a file-based routing system to match URLs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Are there any pitfalls or limigtations to Razor pages?

A

Razor Pages are less flexible than the MVC Framework, which makes them unsuitable for complex applications. Razor Pages can be used only to generate HTML responses and cannot be used to create RESTful web services.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Are there any alternatives to razor pages?

A

The MVC Framework’s approach of controllers and views can be used instead of Razor Pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

MVC framework vs razor pages

A

As you learn how Razor Pages work, you will see they share common functionality with the MVC Framework. In fact, Razor Pages are typically described as a simplification of the MVC Framework—which is true—but that doesn’t give any sense of why Razor Pages can be useful.
The MVC Framework solves every problem in the same way: a controller defines action methods that select views to produce responses. It is a solution that works because it is so flexible: the controller can define multiple action methods that respond to different requests, the action method can decide which view will be used as the request is being processed, and the view can depend on private or shared partial views to produce its response.
Not every feature in web applications needs the flexibility of the MVC Framework. For many features, a single action method will be used to handle a wide range of requests, all of which are dealt with using the same view. Razor Pages offer a more focused approach that ties together markup and C# code, sacrificing flexibility for focus.
But Razor Pages have limitations. Razor Pages tend to start out focusing on a single feature but slowly grow out of control as enhancements are made. And, unlike MVC controllers, Razor Pages cannot be used to create web services.
You don’t have to choose just one model because the MVC Framework and Razor Pages coexist, as demonstrated in this chapter. This means that self-contained features can be easily developed with Razor Pages, leaving the more complex aspects of an application to be implemented using the MVC controllers and actions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What syntax do razor pages use?

A

Razor Pages use the Razor syntax

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does @functions do in Razor pages?

A

@functions directive is used to define the C# code that supports the Razor content in the same file

Example:

@functions {

public class IndexModel: PageModel {

    private DataContext context;

    public Product Product { get; set; }

    public IndexModel(DataContext ctx) {

        context = ctx;

    }

    public async Task OnGetAsync(long id = 1) {

        Product = await context.Products.FindAsync(id);

    }

}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

URL Routing in Razor pages?

A

URL routing for Razor Pages is based on the file name and location, relative to the Pages folder. The Razor Page in Listing 23-4 is in a file named Index.cshtml, in the Pages folder, which means that it will handle requests for the /index. The routing convention can be overridden.

17
Q

@model diractive in Razor pages?

A

In a Razor Page, the @model directive is used to select a page model class, rather than identifying the type of the object provided by an action method. The @model directive in Listing 23-4 selects the IndexModel class.

@model IndexModel

The page model is defined within the @functions directive and is derived from the PageModel class, like this:

@functions {

public class IndexModel: PageModel {

When the Razor Page is selected to handle an HTTP request, a new instance of the page model class is created, and dependency injection is used to resolve any dependencies that have been declared using constructor parameters, using the features described in Chapter 14. The IndexModel class declares a dependency on the DataContext service created in Chapter 18, which allows it to access the data in the database.

public IndexModel(DataContext ctx) {

context = ctx;

}

After the page model object has been created, a handler method is invoked. The name of the handler method is On, followed by the HTTP method for the request so that the OnGet method is invoked when the Razor Page is selected to handle an HTTP GET request. Handler methods can be asynchronous, in which case a GET request will invoke the OnGetAsync method, which is the method implemented by the IndexModel class.

public async Task OnGetAsync(long id = 1) {

Product = await context.Products.FindAsync(id);

}

Values for the handler method parameters are obtained from the HTTP request using the model binding process, which is described in detail in Chapter 28. The OnGetAsync method receives the value for its id parameters from the model binder, which it uses to query the database and assign the result to its Product property.