Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Workshop: Building an Enterprise

Application with ASP.NET Core MVC


Web APP Theme: SIDJEME

Lab11: Diagnosing Runtime Application Issues


Exercise 1: Diagnostics Middleware
Scenario
In this exercise, you will explore the different options offered in Asp.Net Core to diagnose
application runtime issues.

In other words, your will discover different built-in middlewares available in the
Microsoft.AspNetCore.Diagnostics package, which is in the Microsoft.AspNetCore.App metapackage.

Task 1: The WelcomePage middleware


1. Open Visual Studio 2019 and in the Get Started Window, select Open Project or Solution
o Location: [Root Repository] \SIDJEME Labs\SIDJEME\SIDJEME.sln
2. Build the solution and ensure there are no errors.
3. Run the application and ensure it works correctly by visiting different application pages.
4. In the Ansej.Sidjeme.Web project, open Startup.cs file.
5. Locate the //TODO: Add Welcome Page Middleware comment and add the
WelcomePageMiddleware.
6. Build and run the solution.
7. Note that a WelcomePage is shown rather than the Application Home page.
8. Try to access other pages in your application for example (http://localhost:57826/wilaya/index)
and note that all paths return the WelcomePage.
This behavior is due to the WelcomePageMiddleware which handles all requests with welcome
page which uses embedded images and fonts to display a rich view.
9. Open Startup.cs file and comment out the line that add the WelcomePageMiddleware.

Task 2: The DeveloperExceptionPage and ExceptionHandler middleware


1. In the Ansej.Sidjeme.Web project, open Startup.cs file.
2. Locate the line of code that check if the current environment is development
if (env.IsDevelopment()) and enables the DeveloperExceptionPage middleware.
This middleware captures synchronous and asynchronous Exception instances from the pipeline
and generates HTML error responses.
3. In the Controllers folder, open HomeController.cs file.
4. At the beginning of the Index action, add a line of code that throws an exception as following:
throw new Exception("Test DeveloperExceptionPage middleware!");
5. Build and run the solution without debugging (Using Ctrl+F5).
6. Note that the exception page is shown with many details for developer which confirms that the
current environment is “Development”.
7. Note the presence of five tabs (Stack, Query, Cookies, Headers and Routing).
8. Click on each tab and review its content.
9. Close the browser.
10. Right click the Ansej.Sidjeme.Web project and select properties.
11. In the project properties window, click on the Debug tab and change the value of
ASPNETCORE_ENVIRONMENT variable from Development to Staging.
12. Build and run the solution without debugging (Using Ctrl+F5).
13. This time, notice that another error page with less details is displayed, since the current
environment is Staging.
This page is returned by the ExceptionHandler middleware as configured in the else block of the
if (env.IsDevelopment()) statement:

else
{
app.UseExceptionHandler("/Home/Error");
}
14. The ExceptionHandler middleware is used to configure a custom error handling page for the
Production environment. The middleware:
o Catches and logs exceptions.
o Re-executes the request in an alternate pipeline for the page or controller indicated.
The request isn't re-executed if the response has started.

In our care the request is re-executed in an alternate pipeline that point to /Home/Error.

15. Open HomeController.cs file, review the Error action and the model used to render the generic
Error view.
16. In the Views/Shared folder, open Error.cshtml view and review its content.
Note: you can change view content or localize it according to the application ui-culture.

Task 3: The StatusCodePages middleware


1. Always in the Ansej.Sidjeme.Web project, open the Startup.cs file.
2. Locate the comment //TODO: Add StatusCodePages middleware, just after the comment,
uncomment the line of code that add the StatusCodePages middleware.
Note: notice the use of a formatted content for the response. The {0} placeholder represents the
http response status code.
3. Build and run the solution.
4. In the Ansej.Sidjeme.Web application browser window, press the F12 key or CTRL+MAJ+I key
combination to show the developer toolbar and select the Network tab.
5. Press the F5 key, and notice that the error page is shown and that the returned status code is
500 (the request was not processed by the StatusCodePages middleware).
6. In the browser, enter a url that doesn’t match any of the configured routes, for example
http://localhost:57826/test/test and note that the response returned corresponds to that
configured for the StatusCodePages middleware. In this case the response is:

Status code page, status code: 404


Exercise 2: Logging Middleware
Scenario
In this exercise, you will explore the different options offered in Asp.Net Core to log what is really
happening in your application even it’s in production.

Task 1: Configure Logging


1. Open Visual Studio 2019 and in the Get Started Window, select Open Project or Solution
o Location: [Root Repository] \SIDJEME Labs\SIDJEME\SIDJEME.sln
2. In the Ansej.Sidjeme.Api project, open Program.cs file.
3. Locate the comment //TODO: Configure logging by clearing Providers and adding
Console and Debug providers, just after the comment use the ConfigureLogging extension
method to configure logging as following:
o Clear all providers
o Add the Console provider
o Add the Debug provider

Task 2: Writing to logs


1. In the Controllers folder, open GenericReferentielApiController.cs file.
2. Locate the comment //TODO: Import Microsoft.Extensions.Logging namespace, just after
the comment import the asked namespace.
3. In the GenericReferentielApiController<T,TKey> class add a constructor parameter of type
ILogger<GenericReferentielApiController<T,TKey>> named logger and use it to initialize a
protected readonly field named _logger as mentioned in the //TODO comments.
4. Open ActiviteController.cs, CommuneController.cs, SecteurActiviteController.cs and
WilayaController.cs files.
5. In each controller class file, correct the constructor’s signature to be the same as that defined in
the base class.
Note: do not forgot to pass the logger parameter in the call of the base class constructor.
6. In the GenericReferentielApiController.cs file, locate the //TODO comments in the different Get
actions (GET/all, GET/paged, GET/{id} and GET/datatable).
7. Using the _logger field add the different logs according to each //TODO comment (Information,
Warning, Debug and Error).
8. Right click the Ansej.Sidjeme.Api project and Select Properties.
9. In the project properties window, select the Debug Tab and change the debug options as
following:
o For the Profile option: select Ansej.Sidjeme.Api
o For the Launch option: select Project
o For the App URL: use http://localhost:52081
10. In the solution Configuration Manager, ensure that the Multiple Startup projects is selected and
that Ansej.Sidjeme.Web and Ansej.Sidjeme.Api are set to Start.
11. Build the solution and ensure there are no errors.
12. Run the solution in the Debug mode (press F5).
13. Ensure that a console window appears, this console application hosts the Ansej.Sidjeme.Api
application as configured in the 9 step.
14. In the Sidjeme App main menu, click Referentiels->Activites.
15. Open the Api Host console application and ensure that the following log message appears:
info: Ansej.Sidjeme.Api.Controllers.ActiviteController[0]
Datatable Api called for type: Activite
16. Also, remark that many other logs are written from Microsoft*** log categories for levels
Information and Warning.
17. Stop debugging.
18. In the Ansej.Sidjeme.Api project, open the appsettings.Development.json file.
19. In the Logging section note that the Information level is used for categories starting with
“System” or “Microsoft”.
20. Also, note that the default level is set to “Debug”.
21. Change the level for “Microsoft” and “System” categories to be Error.
22. Repeat steps from 12 to 15, and notice that Microsoft categories logs doesn’t appear.
23. In the Activités datatable, edit any activite and click the Secteur Activite dropdown list.
24. Open Api Host console application and ensure that Information logs written for the GET/paged
action appear.
25. Open a new browser, in the address type:
http://localhost:52081/api/secteuractivite/paged?page=0
26. Open Api Host console application and ensure that a fail or error log message appears, because
the page parameter value was less than one.
27. Return to the browser, in the address bar type:
28. http://localhost:52081/api/secteuractivite/paged?pagesize=1200
29. Open Api Host console application and ensure that a warning log message appears, because the
pageSize parameter value was greater than the value defined in the MAX_PAGE_SIZE constant.
30. Also, note that all the debug messages you write appear.
31. Stop debugging.
32. In the Ansej.Sidjeme.Api project, open the appsettings.json file.
33. In the Logging section note that the Information level is used for categories starting with
“Microsoft” but the level Warning is set for the "Microsoft.Hosting.Lifetime" category.
34. Also, note that the default level is set to “Information”.
35. Change the level for “Microsoft” and "Microsoft.Hosting.Lifetime" categories to be Error.
36. Right click the Ansej.Sidjeme.Api project and Select Properties.
37. In the project properties window, select the Debug Tab and change the debug options as
following:
o In the Environment variables set the value of ASPNETCORE_ENVIRONMENT variable to
Production.
38. Build and run the solution.
39. Repeat steps from 25 to 29.
40. In Api Host console application, ensure that all the expected log messages appear except the
Debug messages and that because the default Level in production (appsettings.json) was
Information so all log messages with level greater than or equal to Information appear.
Note: for more information about log level values, review the LogLevel enumeration.
41. Stop debugging.

You might also like