title
stringlengths
3
46
content
stringlengths
0
1.6k
17:289
CanTrack is true only if consent is required and has not been given yet. When the consent cookie is detected, CanTrack is set to false. This way, showBanner is true only if consent is required and has not been given yet. Therefore, it tells us whether to ask the user for consent.
17:290
The options for the consent module are contained in a CookiePolicyOptions instance that must be configured manually with the options framework. The following code snippet shows the default configuration code scaffolded by Visual Studio that configures CookiePolicyOptions in the code, instead of using the configuration file:
17:291
builder.Services.Configure<CookiePolicyOptions>(options =>
17:292
{
17:293
options.CheckConsentNeeded = context => true;
17:294
});
17:295
17:296
UseAuthentication enables authentication schemes and only appears if you select an authentication scheme when the project is created. More specifically, this middleware decodes the authorization tokens (authorization cookies, bearer tokens, etc.), and it uses the information it contains to build a ClaimsPrincipal object that is placed in the HttpContext.User property.
17:297
Specific authentication schemes can be enabled by configuring the options objects in the host building stage, as shown here:
17:298
builder.Services.AddAuthentication(o =>
17:299
{
17:300
o.DefaultScheme =
17:301
CookieAuthenticationDefaults.AuthenticationScheme;
17:302
})
17:303
.AddCookie(o =>
17:304
{
17:305
o.Cookie.Name = `my_cookie`;
17:306
})
17:307
.AddJwtBearer(o =>
17:308
{
17:309
...
17:310
});
17:311
17:312
The preceding code specifies a custom authentication cookie name and adds JWT-based authentication for the REST services contained in the application. Both AddCookie and AddJwtBearer have overloads that accept the name of the authentication scheme before the action, which is where you can define the authentication scheme options. Since the authentication scheme name is necessary for referring to a specific authentication scheme, when it is not specified, a default name is used:
17:313
17:314
The standard name contained in CookieAuthenticationDefaults.AuthenticationScheme for cookie authentication
17:315
The standard name contained in JwtBearerDefaults.AuthenticationScheme for JWT authentication
17:316
17:317
The name that’s passed into o.DefaultScheme selects the authentication scheme, used to fill the User property of HttpContext. Together with DefaultScheme, other properties also allow more advanced customizations.
17:318
For more information about JWT authentication, please refer to the ASP.NET Core service authorization subsection of Chapter 15, Applying Service-Oriented Architectures with .NET.
17:319
If you just specify builder.Services.AddAuthentication(), a cookie-based authentication with default parameters is assumed.
17:320
UseAuthorization enables authorization based on the Authorize attribute. Options can be configured by adding builder.Services.AddAuthorization to the host building stage. These options allow you to define the policies for claims-based authorization.
17:321
UseRouting and UseEndpoints handle the so-called ASP.NET Core endpoints. An endpoint is an abstraction of a handler that serves specific classes of URLs. These URLs are transformed into an Endpoint instance with patterns. When a pattern matches a URL, an Endpoint instance is created and filled with both the pattern’s name and the data that was extracted from the URL. This is a consequence of matching URL parts with named parts of the pattern. This can be seen in the following code snippet:
17:322
Request path: /UnitedStates/NewYork
17:323
Pattern: Name=`location`, match=`/{Country}/{Town}`
17:324
Endpoint: DisplayName=`Location`, Country=`UnitedStates`, Town=`NewYork`
17:325
17:326
UseRouting adds a module that processes the request path to get the request Endpoint instance and adds it to the HttpContext.Features dictionary under the IEndpointFeature type. The actual Endpoint instance is contained in the Endpoint property of IEndpointFeature.
17:327
Each pattern also contains the handler that should process all the requests that match the pattern. This handler is passed to Endpoint when it is created.
17:328
On the other hand, UseEndpoints adds the middleware that executes the route determined by the UseRouting logic. It is placed at the end of the pipeline, since its middleware produces the final response. Splitting the routing logic into two separate middleware modules enables authorization middleware to sit in between them and, based on the matched endpoint, to decide whether to pass the request to the UseEndpoints middleware for its normal execution, or whether to return a 401 (Unauthorized)/403 (Forbidden) response immediately.
17:329
UseAuthorization must always be placed after both UseAuthentication and UseRouting because it needs both the HttpContext.User that is filled by UseAuthentication and the handler selected by UseRouting, in order to verify whether a user is authorized to access the selected request handler.
17:330
As the following code snippet shows, patterns are processed in the UseRouting middleware, but they are listed in the UseEndpoints method. While it might appear strange that URL patterns are not defined directly in the middleware that uses them, this was done mainly for coherence with the previous ASP.NET Core versions. In fact, previous versions contained no method analogous to UseRouting and, instead, some unique middleware at the end of the pipeline. In the new version, patterns are still defined at the end of the pipeline for coherence with previous versions, but now, UseEndpoints just creates a data structure containing all patterns when the application starts. Then, this data structure is processed by the UseRouting middleware, as shown in the following code:
17:331
app.UseRouting();
17:332
app.UseAuthentication();
17:333
app.UseAuthorization();
17:334
app.MapControllerRoute(
17:335
name: `default`,
17:336
pattern: `{controller=Home}/{action=Index}/{id?}`);
17:337
17:338
Where app.MapControllerRoute is a shortcut for:
17:339
app.UseEndpoints(endpoints =>
17:340
{
17:341
endpoints.MapControllerRoute(
17:342
name: `default`,
17:343
pattern: `{controller=Home}/{action=Index}/{id?}`);
17:344
17:345
17:346
});
17:347
17:348
This shortcut was introduced with the 6.0 version of .NET.
17:349
MapControllerRoute defines the patterns associated with the MVC engine, which will be described in the next subsection. Other methods define other types of patterns. A call such as .MapHub<MyHub>(`/chat`) maps paths to hubs that handle SignalR, an abstraction built on top of WebSocket, whereas .MapHealthChecks(`/health`) maps paths to ASP.NET Core components that return application health data.
17:350
You can also directly map a pattern to a custom handler with .MapGet, which intercepts GET requests, and .MapPost, which intercepts POST requests. This is called route to code. The following is an example of MapGet:
17:351
MapGet(`hello/{country}`, context =>
17:352
context.Response.WriteAsync(
17:353
$`Selected country is {context.GetRouteValue(`country`)}`));
17:354
17:355
We can also write app.MapGet(...) directly, since there are shortcuts for MapGet, MapPost, and so on.
17:356
All these shortcuts, together with the new features, have been named Minimal API. They offer a lean approach for simpler applications, which is relevant for architects considering performance optimization and API design, particularly in IoT and microservices scenarios.
17:357
Moreover, MapGet, MapPost, and suchlike have been enhanced, and now they have overloads whose lambda returns the result directly to add to the response with no need to call context.Response.WriteAsync. If the result isn’t a string, it is automatically converted into JSON, and the response Content-Type is set to application/json. For more complex needs, Minimal APIs can use the static methods of the Results class that supports all return types supported by ASP.NET Core controllers. The following is an example of Results class usage:
17:358
app.MapGet(`/web-site-conditions`, () =>
17:360
17:361
Patterns are processed in the order in which they are defined until a matching pattern is found. Since the authentication/authorization middleware is placed after the routing middleware, it can process the Endpoint request to verify whether the current user has the required authorizations to execute the Endpoint handler.
17:362
Otherwise, a 401 (Unauthorized) or 403 (Forbidden) response is immediately returned. Only requests that survive authentication and authorization have their handlers executed by the UseEndpoints middleware.
17:363
The Minimal API supports the automatic generation of the OpenAPI metadata we described in Chapter 15, Applying Service-Oriented Architectures with .NET. They also support Ahead-of-Time (AOT) compilation during the application publication. This way, applications are immediately compiled in the target CPU language, saving the time needed by a just-in-time compilation.
17:364
Moreover, since AOT runs at publication time, it can perform better code optimizations, and in particular, it can trim DLL unused code. In general, AOT is not supported by controller-based applications since they make greater use of reflection.
17:365
Therefore, Minimal APIs are targeted to simple and fast applications, running on small devices such as IoT applications, where, on one hand, speed and reduced application size are fundamental, and on the other hand, the benefit of structuring code through controllers is negligible. We will not describe Minimal APIs in great detail, since this book targets mainly business and enterprise applications.
17:366
It is worth mentioning that in the last .NET version, a new ASP.NET Core API project was added that scaffolds an application based on the Minimal API.
17:367
Like the ASP.NET Core RESTful API described in Chapter 15, ASP.NET Core MVC also uses attributes placed on controllers or controller methods to specify authorization rules. However, an instance of AuthorizeAttribute can also be added to a pattern to apply its authorization constraints to all the URLs matching that pattern, as shown in the following example:
17:368
endpoints
17:369
.MapHealthChecks(`/health`)
17:370
.RequireAuthorization(new AuthorizeAttribute(){ Roles = `admin`, });
17:371
17:372
The previous code makes the health check path available only to administrative users.
17:373
It is also worth mentioning the .UseCors() middleware, which enables the application to handle CORS policies. We will discuss it in the Communication with the server section in Chapter 19, Client Frameworks: Blazor.
17:374
Having described the basic structure of the ASP.NET Core framework, we can now move on to more MVC-specific features. The next subsection describes controllers and explains how they interact with the UI components, known as Views, through ViewModels.
17:375
Defining controllers and ViewModels
17:376
In ASP.NET Core MVC, controllers and ViewModels are central to handling requests, presenting data, and handling the whole user-application interactions. Let’s start by understanding how requests issued at specific paths are passed to controllers.
17:377
The various .MapControllerRoute calls associate URL patterns with controllers and their methods, where controllers are classes that inherit from the Microsoft.AspNetCore.Mvc.Controller class. Controllers are discovered by inspecting all of the application’s .dll files and are added to the DI engine. This job is performed by the call to builder.Services.AddControllersWithViews in the Program.cs file.
17:378
The pipeline module that’s added by UseEndpoints takes the controller’s name from the controller pattern variable, and the name of the controller method to invoke from the action pattern variable. Since, by convention, all controller names are expected to end with the Controller suffix, the actual controller type name is obtained from the name found in the controller variable by adding this suffix. Hence, for instance, if the name found in controller is Home, then the UseEndpoints module tries to get an instance of the HomeController type from the DI engine. All of the controller public methods can be selected by the routing rules. The use of a controller public method can be prevented by decorating it with the [NonAction] attribute. All controller methods available to the routing rules are called action methods.
17:379
MVC controllers work like the API controllers that we described in the Implementing REST services with ASP.NET Core subsection in Chapter 15, Applying Service-Oriented Architectures with .NET. The only difference is that API controllers are expected to produce JSON or XML, while MVC controllers are expected to produce HTML. For this reason, while API controllers inherit from the ControllerBase class, MVC controllers inherit from the Controller class, which, in turn, inherits from the ControllerBase class and adds its methods, which are useful for HTML generation, such as invoking views, as described in the next subsection, and creating a redirect response.
17:380
MVC controllers can also use a routing technique similar to one of the API controllers, that is, routing based on controllers and controller method attributes. This behavior is enabled by calling the app.MapControllers() method in the pipeline definition code in Program.cs. If this call is placed before all other app.MapControllerRoute calls, then the controller routes have priority over MapControllerRoute patterns; otherwise, the opposite is true.
17:381
MapControllerRoute has the advantage of deciding in a single place the whole paths used by the whole application. This way, you can optimize all application paths for a search engine, or simply for better user navigation, by changing a few lines of code in a single place. For these reasons, MapControllerRoute is almost always used in MVC applications. However, MapControllerRoute is rarely used with the REST API because the priority of the REST API is to avoid changes in the associations between paths and controllers, since they might prevent existing clients from working properly.
17:382
All the attributes we have seen for API controllers can also be used with MVC controllers and action methods (HttpGet, HttpPost, …, Authorize, and so on). Developers can write their own custom attributes by inheriting from the ActionFilter class or other derived classes. I will not give details on this right now, but these details can be found in the official documentation, which is referred to in the Further reading section.
17:383
When the UseEndpoints module invokes a controller, all of its constructor parameters are filled by the DI engine, since the controller instance itself is returned by the DI engine, and since DI automatically fills constructor parameters with DI in a recursive fashion.
17:384
Action methods take both their input and services from their parameters, so it is crucial to understand how these parameters are filled by ASP.NET Core. They are taken from the following sources:
17:385
17:386
Request headers
17:387
Variables in the pattern matched by the current request
17:388
Query string parameters
17:389
Form parameters (in the case of POST requests)