title
stringlengths
3
46
content
stringlengths
0
1.6k
17:189
`IIS Express`: {
17:190
`commandName`: `IISExpress`,
17:191
`launchBrowser`: true,
17:192
`environmentVariables`: {
17:193
`ASPNETCORE_ENVIRONMENT`: `Development`
17:194
}
17:195
},
17:196
...
17:197
...
17:198
}
17:199
}
17:200
}
17:201
17:202
The named groups of settings are under the profiles properties. There, you can choose where to host the application (IIS Express), where to launch the browser, and the values of some environment variables.
17:203
The current environment that’s been loaded from the ASPNETCORE_ENVIRONMENT operating system environment variable is available in the app.Environment property during the ASP.NET Core pipeline definition.
17:204
app.Environment.IsEnvironment(string environmentName) checks whether the current value of ASPNETCORE_ENVIRONMENT is environmentName. There are also specific shortcuts for testing development (.IsDevelopment()), production (.IsProduction()), and staging (.IsStaging()). The app.Environment property also contains the current root directory of the ASP.NET Core application (.WebRootPath) and the directory reserved for the static files (.ContentRootPath) that are served as is by the web server (CSS, JavaScript, images, and so on).
17:205
Both launchSettings.json and all publish profiles can be accessed as children of the Properties node in Visual Studio Explorer, as shown in the following screenshot:
17:206
17:207
Figure 17.5: Launch settings file
17:208
Understanding how to map the merged configuration settings to .NET objects is key for effective data management in ASP.NET Core applications.
17:209
Once appsettings.json and appsettings.[EnvironmentName].json have been loaded, the configuration tree resulting from their merge can be mapped to the properties of .NET objects. For example, let’s suppose we have an Email section of the appsettings file that contains all of the information needed to connect to an email server, as shown here:
17:210
{
17:211
`ConnectionStrings`: {
17:212
`DefaultConnection`: `....`
17:213
},
17:214
`Logging`: {
17:215
`LogLevel`: {
17:216
`Default`: `Warning`
17:217
}
17:218
},
17:219
`Email`: {
17:220
`FromName`: `MyName`,
17:221
`FromAddress`: `[email protected]`,
17:222
`LocalDomain`: `smtps.MyDomain.com`,
17:223
`MailServerAddress`: `smtps.MyDomain.com`,
17:224
`MailServerPort`: `465`,
17:225
`UserId`: `[email protected]`,
17:226
`UserPassword`: `mypassword`
17:227
}
17:228
17:229
Then, the whole Email section can be mapped to an instance of the following class:
17:230
public class EmailConfig
17:231
{
17:232
public String FromName { get; set; }
17:233
public String FromAddress { get; set; }
17:234
public String LocalDomain { get; set; }
17:235
public String MailServerAddress { get; set; }
17:236
public String MailServerPort { get; set; }
17:237
public String UserId { get; set; }
17:238
public String UserPassword { get; set; }
17:239
}
17:240
17:241
The code that performs the mapping must be inserted in the host building stage, since the EmailConfig instance will be available through DI. The code we need is shown here:
17:242
Var builder = WebApplication.CreateBuilder(args);
17:243
....
17:244
builder.Services.Configure<EmailConfig>(Configuration.GetSection(`Email`));
17:245
..
17:246
17:247
Once we’ve configured the preceding settings, classes that need EmailConfig data must declare an IOptions<EmailConfig> options constructor parameter that will be provided by the DI engine. An EmailConfig instance is contained in options.Value.
17:248
It is worth mentioning that the option classes’ properties can be applied to the same validation attributes we will use for ViewModels (see the Server-side and client-side validation subsection).
17:249
The next subsection describes the basic ASP.NET Core pipeline modules needed by an ASP.NET Core MVC application.
17:250
Defining the ASP.NET Core pipeline
17:251
Understanding the ASP.NET Core pipeline is key to customizing application behavior. When you create a new ASP.NET Core MVC project in Visual Studio, a standard pipeline is created in the Program.cs file. There, if needed, you can add further middleware or change the configuration of the existing middleware.
17:252
The initial pipeline definition code handles errors and performs basic HTTPS configuration:
17:253
if (app.Environment.IsDevelopment())
17:254
{
17:255
17:256
17:257
}
17:258
else //this is not part of the project template, but it is worth adding it
17:259
{
17:260
app.UseDeveloperExceptionPage();
17:261
}
17:262
app.UseHttpsRedirection();
17:263
17:264
If there are errors, and if the application is in a development environment, the module installed by UseDeveloperExceptionPage adds a detailed error report to the response. This module is a valuable debugging tool.
17:265
If an error occurs when the application is not in development mode, UseExceptionHandler restores the request processing from the path it receives as an argument, that is, from /Home/Error. In other words, it simulates a new request with the /Home/Error path. This request is pushed into the standard MVC processing until it reaches the endpoint associated with the /Home/Error path, where the developer is expected to place the custom code that handles the error.
17:266
When the application is not in development, UseHsts adds the Strict-Transport-Security header to the response, which informs the browser that the application must only be accessed with HTTPS. After this declaration, compliant browsers should automatically convert any HTTP request of the application into an HTTPS request for the time specified in the Strict-Transport-Security header. By default, UseHsts specifies 30 days as the time in the header, but you can specify a different time and other header parameters by passing UseHsts a lambda that configures an options object:
17:267
builder.Services.AddHsts(options => {
17:268
...
17:269
options.MaxAge = TimeSpan.FromDays(60);
17:270
...
17:271
});
17:272
17:273
UseHttpsRedirection causes an automatic redirection to an HTTPS URL when an HTTP URL is received, in a way that forces a secure connection. Once the first HTTPS secure connection is established, the Strict-Transport-Security header prevents future redirections that might be used to perform man-in-the-middle attacks.
17:274
The following code shows the remainder of the default pipeline:
17:275
app.UseStaticFiles();
17:276
// not in the default template but needed in all countries of the European Union
17:277
app.UseCookiePolicy();
17:278
app.UseRouting();
17:279
app.UseAuthentication();
17:280
app.UseAuthorization();
17:281
...
17:282
17:283
UseStaticFiles makes all files contained in the wwwroot folder of the project (typically CSS, JavaScript, images, and font files) accessible from the web through their actual path.
17:284
UseCookiePolicy has been removed in the .NET 5-8 templates, but you can still add it manually. It ensures that cookies are processed by the ASP.NET Core pipeline, but only if the user has given consent for cookie usage. Consent to cookie usage is given through a consent cookie; that is, cookie processing is enabled only if this consent cookie is found among the request cookies. This cookie must be created by JavaScript when the user clicks a consent button. The whole string that contains both the consent cookie’s name and its contents can be retrieved from HttpContext.Features, as shown in the following snippet:
17:285
var consentFeature = context.Features.Get<ITrackingConsentFeature>();
17:286
var showBanner = !consentFeature?.CanTrack ?? false;
17:287
var cookieString = consentFeature?.CreateConsentCookie();
17:288