title
stringlengths
3
46
content
stringlengths
0
1.6k
17:89
app.Use(async (context, next) =>
17:90
{
17:91
...
17:92
await next(context);
17:93
});
17:94
17:95
In general, each piece of middleware processes the HttpContext instance that was passed by the previous module in the pipeline, and then it calls await _next.Invoke(context) to invoke the modules in the remainder of the pipeline. When the other modules have finished their processing and the response for the client has been prepared, each module can perform further post-processing of the response in the code that follows the _next.Invoke(context) call.
17:96
Modules are registered in the ASP.NET Core pipeline by calling the UseMiddleware<T> method of the built host, as shown here:
17:97
var app = builder.Build();
17:98
...
17:99
app.UseMiddleware<MyCustomModule>
17:100
...
17:101
app.Run();
17:102
17:103
Middleware modules are inserted into the pipeline in the same order when UseMiddleware is called. Since each functionality that’s added to an application might require several modules and operations other than adding modules, you usually define an IApplicationBuilder extension such as UseMyFunctionality, as shown in the following code:
17:104
public static class MyMiddlewareExtensions
17:105
{
17:106
public static IApplicationBuilder UseMyFunctionality(this
17:107
IApplicationBuilder builder,...)
17:108
{
17:109
//other code
17:110
...
17:111
builder.UseMiddleware<MyModule1>();
17:112
builder.UseMiddleware<MyModule2>();
17:113
...
17:114
//Other code
17:115
...
17:116
return builder;
17:117
}
17:118
}
17:119
17:120
After that, the whole functionality can be added to the application by calling app.UseMyFunctionality(...). For instance, the ASP.NET Core MVC functionality can be added to the ASP.NET Core pipeline by calling app.UseEndpoints(....).
17:121
Often, functionalities that are added with each app.Use... require that some .NET types are added to the application DI engine. In these cases, we also define an IServiceCollection extension named AddMyFunctionality, which must be called by builder.Services in Program.cs.
17:122
For instance, ASP.NET Core MVC requires a call such as the following:
17:123
builder.Services.AddControllersWithViews(o =>
17:124
{
17:125
//set here MVC options by modifying the o option parameter
17:126
}
17:127
17:128
If you don’t need to change the default MVC options, you can simply call builder.Services.AddControllersWithViews().
17:129
The next subsection describes another important feature of the ASP.NET Core framework – namely, how to handle application configuration data.
17:130
Loading configuration data and using it with the options framework
17:131
Understanding how ASP.NET Core applications handle configuration is crucial for effective application setup. In the default .NET template where an ASP.NET Core application starts, it reads configuration information (such as a database connection string) from the appsettings.json and appsettings.[EnvironmentName].json files, where EnvironmentName is a string value that depends on where the application is deployed.
17:132
Typical values for the EnvironmentName string are as follows:
17:133
17:134
Production is used for production deployment
17:135
Development is used during development
17:136
Staging is used when the application is tested in staging
17:137
17:138
The two JSON trees that were extracted from the appsettings.json and appsettings.[EnvironmentName].json files are merged into a unique tree, where the values contained in [EnvironmentName].json override the values contained in the corresponding paths of appsettings.json. This way, the application can be run with different configurations in different deployment environments. In particular, you can use a different database connection string and, hence, a different database instance in each different environment.
17:139
17:140
Figure 17.2: Configuration files merging
17:141
Configuration information can also be passed from other sources. Given a lack of space, we list here all the other possibilities without discussing them:
17:142
17:143
XML files
17:144
.ini files
17:145
Operating system environment variables. The variable name is the name of the setting prefixed by the ASPNETCORE_ string, while the variable value is the setting value.
17:146
Command-line arguments of a dotnet command that invokes the application.
17:147
An in-memory collection of key-value pairs
17:148
17:149
The JSON format is, in my opinion, the most practical and readable, but JSON, XML, and .ini are substantially equivalent, and choosing among them is just a matter of preference.
17:150
In memory, collections of key-value pairs offer the possibility of taking data from a database, so they are useful options for those parameters that need to be changed by an administrator while the application is running.
17:151
Finally, command-line arguments and environment variables are good options when the application can’t easily access disk storage – for instance, in the case of deployments running in a Kubernetes cluster. In fact, environment variables can be passed as parameters in the Kubernetes .yaml files (see the ReplicaSets and Deployments section of Chapter 20, Kubernetes). They are also an acceptable choice for passing sensitive data that it is not adequate to store in files in a plain format.
17:152
From version 8 onward, ASP.NET Core allows you to set Kestrel HTTP and HTTPS listening ports as configuration variables. More specifically, HTTP_PORTS contains a semicolon-separated list of all Kestrel HTTP listening ports, while HTTPS_PORTS contains a semicolon-separated list of all HTTPs listening ports whose defaults are the usual HTTP and HTTPs ports, that is, 80 and 443, respectively.
17:153
The [EnvironmentName] string itself is taken from the ENVIRONMENT configuration setting. Clearly, since it is needed to decide which configuration files to use, it cannot be contained in a configuration file, so it must be taken from the ASPNETCORE_ENVIRONMENT operating system environment variable, or from the arguments of the dotnet command used to launch the application.
17:154
17:155
When the application is deployed to IIS instead of being launched as a standalone program, ASPNETCORE_ENVIRONMENT can’t be passed on the dotnet command line.
17:156
17:157
In this case, it can be set in the IIS application settings. This can be done after the applications have been deployed, by clicking on the Configuration Editor and then selecting the system.webServer/aspNetCore section. In the window that opens, select environmentVariables, and then add the ASPNETCORE_ENVIRONMENT variable with its value.
17:158
17:159
Figure 17.3: Changing ASPNETCORE_ENVIRONMENT in IIS
17:160
However, when the application is modified and deployed again, the setting is reset to its default value, which is Production, and it must be set again.
17:161
A better choice is to modify the publish profile in Visual Studio, as follows:
17:162
17:163
During Visual Studio deployment, Visual Studio’s Publish wizard creates an XML publish profile. Once the preferred deployment type (Azure, Web Deploy, folder, and so on) has been chosen, and before publishing, you can edit the publish settings by choosing Edit from the More actions dropdown in the window that appears.
17:164
Once you have your publish file properly set, in Visual Studio Solution Explorer, open the profile that you just prepared with the Visual Studio wizard. Profiles are saved in the Properties/PublishProfiles/<profile name>.pubxml path of the project folder.
17:165
Then, edit the profile with a text editor, and add an XML property such as <EnvironmentName>Staging</EnvironmentName>. Since all the already defined publish profiles can be selected during the application’s publication, you can define a different publish profile for each of your environments, and then, you can select the one you need during each publication.
17:166
17:167
The value you must set ASPNETCORE_ENVIRONMENT to during deployment can also be specified in the Visual Studio ASP.NET Core project file (.csproj) of your application, by adding the following code:
17:168
<PropertyGroup>
17:169
<EnvironmentName>Staging</EnvironmentName>
17:170
</PropertyGroup>
17:171
17:172
This is the simplest way to do ASPNETCORE_ENVIRONMENT, but not the most modular, since we are forced to change the application code before publishing to a different environment.
17:173
Specifying the environment either in the publish profile or the project file works only for deployment types based on direct communication between Visual Studio and the web server, as in other deployment types, Visual Studio cannot inform the web server on how to set ASPNETCORE_ENVIRONMENT or on how to pass the environment when the application is launched. At the time of writing, the techniques described work just for Web Deploy or when publishing on Azure.
17:174
During development in Visual Studio, the value to give to ASPNETCORE_ENVIRONMENT when the application is run can be specified in the PropertieslaunchSettings.json file of the ASP.NET Core project. The launchSettings.json file contains several named groups of settings. These settings configure how to launch the web application when it is run from Visual Studio. You can choose to apply all the settings of a group by selecting the group name with the drop-down list next to Visual Studio’s run button:
17:175
17:176
Figure 17.4: Choice of launch settings group
17:177
Your selection from this drop-down list will be visible on the run button, with the default selection being IIS Express.
17:178
Consider a development environment setup, as illustrated in this typical launchSettings.json file:
17:179
{
17:180
`iisSettings`: {
17:181
`windowsAuthentication`: false,
17:182
`anonymousAuthentication`: true,
17:183
`iisExpress`: {
17:184
`applicationUrl`: `http://localhost:2575`,
17:185
`sslPort`: 44393
17:186
}
17:187
},
17:188
`profiles`: {