title
stringlengths
3
46
content
stringlengths
0
1.6k
17:390
The request body
17:391
Dependency injection (DI), in case of services needed to process the request
17:392
17:393
While the parameters filled with DI are matched by type, all other parameters are matched by name while ignoring the letter casing. That is, the action method parameter name must match the header, query string, form, or pattern variable. In turn, pattern variables are filled by matching the pattern with the request path.
17:394
When the parameter is a complex type, the behavior depends on the source.
17:395
If the source is the request body, a formatter adequate for the request Content-Type is selected. Formatters are software modules capable of building complex entities, starting from a text representation of them. As a default, the request body is taken as a source for selected Content-Types, such as application/json and binary MIME types, because each such MIME type requires a different deserialization algorithm that is specific to it.
17:396
If the source is not the request body, an algorithm called model binding is used to fill all complex object public properties instead.
17:397
The model binding algorithm searches for a match in each property (remember that just properties are mapped; fields are not), using the property name for the match. In the case of nested complex types, a match is searched for each nested property’s path, and the name associated with the path is obtained by chaining all the property names in the path and separating them with dots. For instance, a parameter whose name is Property1.Property2.Property3…Propertyn is mapped with the Propertyn property that is in the following path of nested object properties: Property1, Property2, ...., Propertyn.
17:398
The name that’s obtained this way must match a header name, pattern variable name, query string parameter name, and so on. For instance, an OfficeAddress property containing a complex Address object would generate names like OfficeAddress.Country and OfficeAddress.Town.
17:399
The model binding algorithm can also fill collections and dictionaries, but due to a lack of space, we can’t describe these cases. However, the Further reading section contains a link to an excellent Phil Haack post that explains them in detail.
17:400
By default, simple type parameters are matched with pattern variables and query string variables, while complex type parameters are matched with form parameters or the request body (depending on their MIME types). However, the preceding defaults can be changed by prefixing the parameters with attributes, as detailed here:
17:401
17:402
[FromForm] forces a match with form parameters
17:403
[FromBody] forces the extraction of data from the request body
17:404
[FromHeader] forces a match with a request header
17:405
[FromRoute] forces a match with pattern variables
17:406
[FromQuery] forces a match with a query string variable
17:407
[FromServices] forces the use of DI
17:408
17:409
It is worth pointing out that versions 7 and 8 of ASP.NET Core have an enhanced Minimal API to support basically the same parameter bindings of a controller’s action methods, as well as all the above parameter attributes.
17:410
During the match, the string that was extracted from the selected source is converted into the type of the action method parameter, using the current thread culture. If either a conversion fails or no match is found for an obligatory action method parameter, then the whole action method invocation process fails, and a 404 response is automatically returned. For instance, in the following example, the id parameter is matched with query string parameters or pattern variables, since it is a simple type, while myclass properties and nested properties are matched with form parameters, since MyClass is a complex type. Finally, myservice is taken from DI, since it is prefixed with the [FromServices] attribute:
17:411
public class HomeController : Controller
17:412
{
17:413
public IActionResult MyMethod(
17:414
int id,
17:415
MyClass myclass,
17:416
[FromServices] MyService myservice)
17:417
{
17:418
...
17:419
17:420
If no match is found for the id parameter, and if the id parameter is declared as obligatory in the MapControllerRoute pattern, a 404 response is automatically returned, since pattern matching fails. It is common to declare parameters as not optional when they must match not-nullable single types. If, instead, no MyService instance is found in the DI container, an exception is thrown because, in this case, the failure doesn’t depend on a wrong request but on a design error.
17:421
MVC controllers return an IActionResult interface or a Task<IActionResult> result if they are declared as async. IActionResult defines the unique method with the ExecuteResultAsync(ActionContext) signature, which, when invoked by the framework, produces the actual response.
17:422
For each different IActionResult, MVC controllers have methods that return them. The most commonly used IActionResult is ViewResult, which is returned by a View method:
17:423
public IActionResult MyMethod(...)
17:424
{
17:425
...
17:426
return View(`myviewName`, MyViewModel)
17:427
}
17:428
17:429
ViewResult is a very common way for a controller to create an HTML response. More specifically, the controller interacts with business/data layers to produce an abstraction of the data that will be shown on the HTML page. This abstraction is an object called a ViewModel. The ViewModel is passed as a second argument to the View method, while the first argument is the name of an HTML template, called View, that is instantiated with the data contained in the ViewModel.
17:430
Summing this up, the MVC controllers’ processing sequence is as follows:
17:431
17:432
The controllers perform some processing to create the ViewModel, which is an abstraction of the data to show on the HTML page.
17:433
Then, the controllers create ViewResult by passing a View name and ViewModel to the View method.
17:434
The MVC framework invokes ViewResult and causes the template contained in the View to be instantiated with the data contained in the ViewModel.
17:435
The result of the template’s instantiation is written in the response with adequate headers.
17:436
17:437
This way, the controller performs the conceptual job of HTML generation by building a ViewModel, while the View – that is, the template – takes care of all the presentation details.
17:438
Views will be described in greater detail in the next subsection, while the Model (ViewModel) View Controller pattern will be discussed in more detail in the Understanding the connection between ASP.NET Core MVC and design principles section in this chapter. Finally, a practical example will be provided in Chapter 18, Implementing Frontend Microservices with ASP.NET Core.
17:439
Another common IActionResult is RedirectResult, which creates a redirect response, hence forcing the browser to move to a specific URL. Redirects are often used once the user has successfully submitted a form that completes a previous operation. In this case, it is common to redirect the user to a page where they can select another operation.
17:440
The simplest way to return RedirectResult is by passing a URL to the Redirect method. This is the advised way to perform a redirect to a URL that is outside the web application. On the other hand, when the URL is within the web application, it is advisable to use the RedirectToAction method, which accepts the controller’s name, the action method name, and the desired parameters for the target action method. This method has several overloads, where each overload omits some of the above parameters. In particular, the controller name can be omitted if the URL we define is handled by the same controller.
17:441
The framework uses this data to compute a URL that causes the desired action method to be invoked with the parameters provided. This way, if the routing rules are changed during the application’s development or maintenance, the new URL is automatically updated by the framework, with no need to modify all occurrences of the old URL in the code.
17:442
The following code shows how to call RedirectToAction:
17:443
return RedirectToAction(`MyActionName`, `MyControllerName`,
17:444
new {par1Name=par1Value,..parNName=parNValue});
17:445
17:446
Another useful IActionResult is ContentResult, which can be created by calling the Content method. ContentResult allows you to write any string to the response and specify its MIME type, as shown in the following example:
17:447
return Content(`this is plain text`, `text/plain`);
17:448
17:449
Finally, the File method returns FileResult, which writes binary data in the response. There are several overloads of this method that allow the specification of a byte array, a stream, or the path of a file, plus the MIME type of the binary data.
17:450
Now, let’s move on to describing how actual HTML is generated in Views.
17:451
Understanding how ASP.NET Core MVC creates the response HTML
17:452
Razor Views
17:453
ASP.NET Core MVC uses a language called Razor to define the HTML templates contained in the Views. Razor views are files that are compiled into .NET classes when they’re first used, when the application has been built, or when the application has been published. By default, both pre compilation on each build and on publish are enabled, but you can also enable runtime compilation so that the Views can be modified once they have been deployed. This option can be enabled by checking the Enable Razor runtime compilation checkbox when the project is created in Visual Studio. You can also disable compilation on each build and on publish by adding the following code to the web application project file:
17:454
<PropertyGroup>
17:455
<TargetFramework> net8.0 </TargetFramework>
17:456
<!-- add code below -->
17:457
<RazorCompileOnBuild>false</RazorCompileOnBuild>
17:458
<RazorCompileOnPublish>false</RazorCompileOnPublish>
17:459
<!-- end of code to add -->
17:460
...
17:461
</PropertyGroup>
17:462
17:463
Views can also be precompiled into Views libraries if you choose a Razor view library project in the window, which appears once you have chosen an ASP.NET Core project.
17:464
Also, following the compilation, Views remain associated with their paths, which become their full names. Each controller has an associated folder under the Views folder with the same name as the controller, which is expected to contain all the Views used by that controller.
17:465
The following screenshot shows the folder associated with a possible HomeController and its Views:
17:466
17:467
Figure 17.6: View folders associated with controllers and the shared folder
17:468
The preceding screenshot also shows the Shared folder, which is expected to contain all the Views or partial views used by several controllers. The controller refers to views in the View method through their paths without the .cshtml extension. If the path starts with /, the path is interpreted as relative to the application root. Otherwise, as a first attempt, the path is interpreted as relative to the folder associated with the controller. If no View is found there, the View is searched for in the Shared folder.
17:469
Hence, for instance, the Privacy.cshtml View file in the preceding screenshot can be referred to from within HomeController as View(`Privacy`, MyViewModel). If the name of the View is the same as the name of the action method, we can simply write View(MyViewModel).
17:470
Razor views are a mix of HTML code with C# code, plus some Razor-specific statements. They usually begin with a header that contains the type of ViewModel that the View is expected to receive:
17:471
@model MyViewModel
17:472
17:473
This declaration may be omitted, but in this case, the view will not be specific to a specific type, and we will not be able to use the model property names in the Razor code.
17:474
Each view may also contain some using statements, whose effect is the same as the using statements of standard code files:
17:475
@model MyViewModel
17:476
@using MyApplication.Models
17:477
17:478
@using statements declared in the special _ViewImports.cshtml file – that is, in the root of the Views folder – are automatically applied to all views.
17:479
Each view can also require instances of types from the DI engine in its header, with the syntax shown here:
17:480
@model MyViewModel
17:481
@using MyApplication.Models
17:482
@inject IViewLocalizer Localizer
17:483
17:484
The preceding code requires an instance of the IViewLocalizer interface and places it in the Localizer variable. The remainder of the View is a mix of C# code, HTML, and Razor control flow statements. Each area of a view can be either in HTML mode or C# mode. The code in a View area that is in HTML mode is interpreted as HTML, while the code in a View area that is in C# mode is interpreted as C#.
17:485
The topic that follows explains the Razor flow of control statements.
17:486
Learning the Razor flow of control statements
17:487
If you want to write some C# code in an HTML area, you can create a C# area with the @{..} Razor flow of a control statement, as shown here:
17:488
@{
17:489
//place C# code here