0% found this document useful (0 votes)
4 views

Lab 04

The document outlines a lab guide for developing controllers in an ASP.NET Core MVC application, detailing tasks such as adding controllers, actions, and configuring routes. It includes step-by-step instructions for implementing features like returning views, handling image files, and redirecting actions. Additionally, it covers the creation of custom routes using attributes and the implementation of an action filter to assist new developers in understanding controller actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab 04

The document outlines a lab guide for developing controllers in an ASP.NET Core MVC application, detailing tasks such as adding controllers, actions, and configuring routes. It includes step-by-step instructions for implementing features like returning views, handling image files, and redirecting actions. Additionally, it covers the creation of custom routes using attributes and the implementation of an action filter to assist new developers in understanding controller actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to main contentgo deploy

M55340A | Module 4

M55340A | Module 4
 Home
 Lab Guide

Lab Guide

Module 4: Developing Controllers


Lab: Developing Controllers
Scenario

You have been asked to add controllers to a new application. The controllers should
include actions that return a view, also add an action that returns the photo as a .jpg file
to show on a webpage, and an action that redirects to another action in another
controller. Additionally, you have been asked to configure routes in a variety of ways.

The members of your development team are new to ASP.NET Core MVC and they find
the use of controller actions confusing. Therefore, you need to help them by adding a
component that displays action parameters in an external file whenever an action runs.
To achieve this, you will add an action filter.
Exercise 1: Adding Controllers and Actions to an MVC Application

Scenario

In this exercise, you will create the MVC controller that handles user operations. You will
also add the following actions:

 Index. This action displays the Index view.


 Display. This action takes an ID to find a single City object. It passes the City
object to the Display view.
 GetImage. This action returns the photo image from the service as a .jpg file.

The main tasks for this exercise are as follows:

 Add controllers to an MVC application


 Add actions to a controller
 Change actions to get a parameter
 Change an action to redirect to another action in another controller
 Use a service
 Store the result in a ViewBag property
 Run the application

Task 1: Add controllers to an MVC application

1. Navigate to D:\Allfiles\Mod04\Labfiles\01_WorldJourney_begin and double-


click WorldJourney.sln.

Note: If a Security Warning for WorldJourney dialog box appears, verify that
the Ask me for every project in this solution check box is cleared, and then
click OK.
2. In Solution Explorer, right-click WorldJourney, point to Add, and then
select New Folder.
3. In the NewFolder box, type Controllers, and then press Enter.
4. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,
right-click the Controllers folder, point to Add, and then select Controller....
5. In the Add New Scaffolded Item dialog box, click MVC Controller - Empty,
and then click Add.
6. In the Add New Item dialog box, in the Name: textbox, type HomeController,
and then click Add (if this is the first controller, it will already be named for you).
7. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,
right-click the Controllers folder, point to Add, and then select Controller....
8. In the Add New Scaffolded Item dialog box, click MVC Controller - Empty,
and then click Add.
9. In the Add New Item dialog box, in the Name: textbox, type CityController, and
then click Add.

Task 2: Add actions to a controller

1. In the CityController class code block, in the Index action code block, locate
the following code:
2. return View();
3. Place the cursor before the located code, and type the following code:
4. ViewData["Page"] = "Search city";
5. In the CityController code window, ensure that the cursor is at the end of
the Index action code block, press Enter, and then type the following code:
6. public IActionResult Details()
7. {
8. }
9. In the Details action code block, type the following code:
10. ViewData["Page"] = "Selected city";
11. City city = null;
12. if (city == null)
13. {
14. return NotFound();
15. }
16.
17. return View(city);
18. Verify that Visual Studio has automatically added a using statement for
the WorldJourney.Models namespace as a result of you referencing
the City type:
19. using WorldJourney.Models;
20. In the CityController code window, ensure that the cursor is at the end of
the Details action code block, press Enter, and then type the following code:
21. public IActionResult GetImage()
22. {
23. }
24. In the GetImage action code block, type the following code:
25. ViewData["Message"] = "display Image";
26. City requestedCity = null;
27. if (requestedCity != null)
28. {
29. string fullPath = "";
30. FileStream fileOnDisk = new FileStream(fullPath, FileMode.Open);
31. byte[] fileBytes;
32. using (BinaryReader br = new BinaryReader(fileOnDisk))
33. {
34. fileBytes = br.ReadBytes((int)fileOnDisk.Length);
35. }
36. return File(fileBytes, requestedCity.ImageMimeType);
37. }
38. else
39. {
40. return NotFound();
41. }
Task 3: Change actions to get a parameter

1. In the CityController class code block, select the following code:


2. public IActionResult Details()
3. Add a parameter by replacing the selected code with the following code:
4. public IActionResult Details(int? id)
5. In the CityController class code block, select the following code:
6. public IActionResult GetImage()
7. Add a parameter by replacing the selected code with the following code.:
8. public IActionResult GetImage(int? cityId)
Task 4: Change an action to redirect to another action in another controller

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


expand Controllers, and then click HomeController.cs.
2. In the HomeController code window, in the Index action code block, select the
following code:
3. return View();
4. Replace the selected code with the following code:
5. return RedirectToAction("Index", "City");
Task 5: Use a service

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


under Controllers, click CityController.cs.
2. In the CityController class code block, locate the following code:
3. public IActionResult Index()
4. Place the mouse cursor before the located code, type the following code, and
then press Enter.
5. private IData _data;
6. private IWebHostEnvironment _environment;
7.
8. public CityController(IData data, IWebHostEnvironment environment)
9. {
10. _data = data;
11. _environment = environment;
12. _data.CityInitializeData();
13. }
14. In the Details action code block, select the following code:
15. City city = null;
16. Replace the selected code with the following code:
17. City city = _data.GetCityById(id);
18. In the GetImage action code block, select the following code:
19. City requestedCity = null;
20. Replace the selected code with the following code:
21. City requestedCity = _data.GetCityById(cityId);
22. In the GetImage action code block, select the following code:
23. string fullPath = "";
24. Replace the selected code with the following code:
25. string webRootpath = _environment.WebRootPath;
26. string folderPath = "\\images\\";
27. string fullPath = webRootpath + folderPath + requestedCity.ImageName;
Task 6: Store the result in a ViewBag property

1. In the CityController class code block, in the Details action code block, locate
the following code:
2. return View(city);
3. Place the mouse cursor before the located code, and type the following code:
4. ViewBag.Title = city.CityName;
Task 7: Run the application

1. In the WorldJourney - Microsoft Visual Studio window, on the File menu,


click Save All.
2. In the WorldJourney - Microsoft Visual Studio window, on the Debug menu,
click Start Without Debugging.

Note: The browser displays the Index action result inside the City controller.
3. In Microsoft Edge, on the Earth image, click the London area. Note the red
arrow at the center of the Earth image (the map's hot area is not very accurate -
you may find you need to click over Scotland or Ireland!).

Note: The browser displays the Details action result inside the City controller.
4. In Microsoft Edge, click Close.

Results: After completing this exercise, you have created MVC controllers that
implement common actions for the City model class in the application.
Exercise 2: Configuring Routes by Using the Routing Table

Scenario

An important design priority for the application is that the visitors should be able to
easily and logically locate cities. To implement these priorities, you have been asked to
configure routes by using the routing table that enables the entry of user-friendly URLs
to access cities.

The main tasks for this exercise are as follows:


 Add a controller with an action
 Run the application
 Register new routes in the routing table
 Run the application and verify that the new route works

Task 1: Add a controller with an action

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


right-click the Controllers folder, point to Add, and then select Controller....
2. In the Add New Scaffolded Item dialog box, click MVC controller - Empty,
and then click Add.
3. In the Add New Item dialog box, in the Name: textbox, type TravelerController,
and then click Add.
4. In the TravelerController class code block, select the following code:
5. public IActionResult Index()
6. {
7. return View();
8. }
9. Replace the selected code with the following code:
10. public IActionResult Index(string name)
11. {
12. ViewBag.VisitorName = name;
13. return View();
14. }
Task 2: Run the application

1. In the WorldJourney - Microsoft Visual Studio window, on the File menu,


click Save All.
2. In the WorldJourney - Microsoft Visual Studio window, on the Debug menu,
click Start Without Debugging.
3. In Microsoft Edge, in the address bar, type http://localhost:[port]/Traveler/Index,
and then press Enter.

Note: In the next task you will register a new route with the routing table. Then,
you will not need to manually enter the Traveler/Index relative URL in the
address bar.
4. In Microsoft Edge, click Close.

Task 3: Register new routes in the routing table

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


click Program.cs.
2. Inside the Program.cs file, select the following code:
3. app.MapDefaultControllerRoute();
4. Replace the selected code with the following code:
5. app.MapControllerRoute(
6. "TravelerRoute",
7. "{controller}/{action}/{name}",
8. new { controller = "Traveler", action = "Index", name = "Katie Bruce" },
9. new { name = "[A-Za-z ]+" }
10. );
11. app.MapControllerRoute(
12. "defaultRoute",
13. "{controller}/{action}/{id?}",
14. new { controller = "Home", action = "Index" },
15. new { id = "[0-9]+" }
16. );
Note: You can replace the default name Katie Bruce with your own name.
Task 4: Run the application and verify the new route works

1. In the WorldJourney - Microsoft Visual Studio window, on the File menu,


click Save All.
2. In the WorldJourney - Microsoft Visual Studio window, on the Debug menu,
click Start Without Debugging.

Note: The name "Katie Bruce" shown in the title comes from the
new "TravelerRoute" route, registered in the routing table.
3. In Microsoft Edge, click Close.

Results: After completing this exercise, you will be able to register new custom routes
in the request pipeline for controllers in the application.
Exercise 3: Configuring Routes by Using Attributes

Scenario

In addition to configuring routes by using the routing table, you have been asked to
configure routes by using attributes as well to enable the entry of user-friendly URLs. In
this exercise you will use custom routes by means of attributes.
Task 1: Apply custom routes to a controller by using attributes

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


under Controllers, click CityController.cs.
2. In the Index action code block, locate the following code:
3. public IActionResult Index()
4. Place the cursor before the located code, press Enter, and then type the following
code:
5. [Route("WorldJourney")]
6. In the Details action code block, locate the following code:
7. public IActionResult Details(int? id)
8. Place the cursor before the located code, press Enter, and then type the following
code:
9. [Route("CityDetails/{id?}")]
Task 2: Run the application and verify the new routes work

1. In the WorldJourney - Microsoft Visual Studio window, on the File menu,


click Save All.
2. In the WorldJourney - Microsoft Visual Studio window, on the Debug menu,
click Start Without Debugging.
3. In Microsoft Edge, right-click the page, and then select View page source.
4. Locate the line of HTML (near the end of the page):
5. <div class="button-center">
6. Find the anchor tag on the next line, and verify that the href attribute
is /WorldJourney:
7. <a href="/WorldJourney">Go Next</a>
8. Close the page source tab.
9. In the normal Microsoft Edge view, click on the Go Next button, and verify that it
takes you to the WorldJourney view.

Note: As a result of applying a custom route to CityController in


the Index action by using
attributes, http://localhost:[port]/WorldJourney should appear in the address
bar.
10. In Microsoft Edge, right-click the page anywhere outside the large graphic, and
then select View page source.
11. Find the map element on the page, which defines the hot areas on the large
graphic.
12. Verify that the value of href attribute for the London hot area is /CityDetails/2.
13. Close the page source tab.
14. In Microsoft Edge, on the Earth image, click the London area (next to the red
arrow at the center of the image), and verify that it takes you to the London
details page.

Note: As a result of applying a custom route to a CityController in


the Details action using
attributes, http://localhost:[port]/CityDetails/2 should appear in the address
bar.
15. In Microsoft Edge, click Close.

Results: After completing this exercise, you have added custom routes to
the City controller by using the Route attribute.
Exercise 4: Adding an Action Filter

Scenario

Your development team is new to ASP.NET Core MVC and is having difficulty in passing
the right parameters to controllers and actions. You need to implement a component
that displays the controller names and action names in an external file to help with this
problem. In this exercise, you will create an action filter for this purpose.

The main tasks for this exercise are as follows:

 Add an action filter class


 Add a handler for the OnActionExecuting event
 Add a handler for the OnActionExecuted event
 Add a handler for the OnResultExecuted event
 Apply the action filter to the controller action
 Run the application and verify that the new filter works

Task 1: Add an action filter class

1. In Solution Explorer, right-click WorldJourney, point to Add, and then


select New Folder.
2. In the NewFolder box, type Filters, and then press Enter.
3. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,
right-click Filters, point to Add, and then select Class....
4. In the Add New Item -- WorldJourney dialog box, in the Name box,
type LogActionFilterAttribute, and then click Add.
5. In LogActionFilterAttribute locate the following code:
6. using System.Threading.Tasks;
7. Ensure that the cursor is at the end of the using
System.Threading.Tasks namespace, press Enter, and then type the following
code:
8. using System.IO;
9. using Microsoft.AspNetCore.Hosting;
10. using Microsoft.AspNetCore.Mvc;
11. using Microsoft.AspNetCore.Mvc.Filters;
12. In the LogActionFilterAttribute class code window, locate the following code:
13. public class LogActionFilterAttribute
14. Add the ActionFilterAttribute as a base class so that it looks like the following:
15. public class LogActionFilterAttribute : ActionFilterAttribute
16. Verify that Visual Studio has automatically added a using statement for
the Microsoft.AspNetCore.Mvc.Filters namespace.
17. In the LogActionFilterAttribute class code block, press Enter, and then type
the following code:
18. private IWebHostEnvironment _environment;
19. private string _contentRootPath;
20. private string _logPath;
21. private string _fileName;
22. private string _fullPath;
23.
24. public LogActionFilterAttribute(IWebHostEnvironment environment)
25. {
26. _environment = environment;
27. _contentRootPath = _environment.ContentRootPath;
28. _logPath = _contentRootPath + "\\LogFile\\";
29. _fileName = $"log {DateTime.Now.ToString("MM-dd-yyyy-H-mm")}.txt";
30. _fullPath = _logPath + _fileName;
31. }
Task 2: Add a handler for the OnActionExecuting event

1. In the LogActionFilterAttribute class code block, ensure that the cursor is at


the end of the LogActionFilterAttribute constructor code block, press Enter,
and then type the following code:
2. public override void OnActionExecuting(ActionExecutingContext filterContext)
3. {
4. }
5. In the OnActionExecuting method code block, press Enter, insert the following
code:
6. Directory.CreateDirectory(_logPath);
7. string actionName = filterContext.ActionDescriptor.RouteValues["action"];
8. string controllerName =
filterContext.ActionDescriptor.RouteValues["controller"];
9. using (FileStream fs = new FileStream(_fullPath, FileMode.Create))
10. {
11. using (StreamWriter sw = new StreamWriter(fs))
12. {
13. sw.WriteLine($"The action {actionName} in {controllerName} controller
started, event fired: OnActionExecuting");
14. }
15. }
Task 3: Add a handler for the OnActionExecuted event
1. In the LogActionFilterAttribute class code block, ensure that the cursor is at
the end of the OnActionExecuting method code block, press Enter, and then
type the following code:
2. public override void OnActionExecuted(ActionExecutedContext filterContext)
3. {
4. }
5. In the OnActionExecuted method code block, press Enter, type the following
code, and then press Enter.
6. string actionName = filterContext.ActionDescriptor.RouteValues["action"];
7. string controllerName =
filterContext.ActionDescriptor.RouteValues["controller"];
8. using (FileStream fs = new FileStream(_fullPath, FileMode.Append))
9. {
10. using (StreamWriter sw = new StreamWriter(fs))
11. {
12. sw.WriteLine($"The action {actionName} in {controllerName} controller
finished, event fired: OnActionExecuted");
13. }
14. }
Task 4: Add a handler for the OnResultExecuted event

1. In the LogActionFilterAttribute class code block, ensure that the cursor is at


the end of the OnActionExecuted method code block, press Enter, and then
type the following code:
2. public override void OnResultExecuted(ResultExecutedContext filterContext)
3. {
4. }
5. In the OnResultExecuted method code block, press Enter, type the following
code, and then press Enter.
6. string actionName = filterContext.ActionDescriptor.RouteValues["action"];
7. string controllerName =
filterContext.ActionDescriptor.RouteValues["controller"];
8. ViewResult result = (ViewResult)filterContext.Result;
9. using (FileStream fs = new FileStream(_fullPath, FileMode.Append))
10. {
11. using (StreamWriter sw = new StreamWriter(fs))
12. {
13. sw.WriteLine($"The action {actionName} in {controllerName} controller
has the following viewData : {result.ViewData.Values.FirstOrDefault()}, event
fired: OnResultExecuted");
14. }
15. }
Task 5: Apply the action filter to the controller action

1. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,


click Program.cs.
2. In the Program.cs code window, locate the following code:
3. builder.Services.AddSingleton<IData, Data>();
4. Place the mouse cursor after the located code, and add the following:
5. builder.Services.AddScoped<LogActionFilterAttribute>();
6. Verify that Visual Studio has automatically added a using statement for
the WorldJourney.Filters namespace.
7. In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer,
expand Controllers, and then click CityController.cs.
8. In the CityController class code block, locate the following code:
9. [Route("WorldJourney")]
10. Place the mouse cursor before the located code, press Enter, and then type the
following code:
11. [ServiceFilter(typeof(LogActionFilterAttribute))]
Task 6: Run the application and verify the new filter works

1. In the WorldJourney - Microsoft Visual Studio window, on the File menu,


click Save All.
2. In the WorldJourney - Microsoft Visual Studio window, on the Debug menu,
click Start Without Debugging.
3. In Microsoft Edge, click on Go Next.
4. In Microsoft Edge, on the Earth image, click the London area (next to the red
arrow).
5. Click Go Back.
6. In Microsoft Edge, click Close.
7. In the WorldJourney - Microsoft Visual Studio window, on the File menu,
click Exit.
8. Navigate to D:\Allfiles\Mod04\Labfiles\01_WorldJourney_begin\LogFile.
There should be one or more log files with names of the form log [date] .txt.
9. Open one of the log files to verify that controller action events have been logged.

Note: The log files contain the output of the action filter.
Results: After completing this exercise, you have created an action filter class that logs
the details of actions, controllers, and parameters to an external log file whenever an
action is called.
01:27:111 hour and 27 minutes remaining on your lab session
Keyboard released from VM

You might also like