Estimated Time: 60 minutes
-
Navigate to [Repository Root]\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.
-
In Solution Explorer, right-click WorldJourney, point to Add, and then select New Folder.
-
In the NewFolder box, type Controllers, and then press Enter.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, right-click the Controllers folder, point to Add, and then select Controller.
-
In the Add Scaffold dialog box, click MVC Controller - Empty, and then click Add.
-
In the Add Empty MVC Controller dialog box, in the Controller name box, type HomeController, and then click Add.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, right-click the Controllers folder, point to Add, and then select Controller.
-
In the Add Scaffold dialog box, click MVC Controller - Empty, and then click Add.
-
In the Add Empty MVC Controller dialog box, in the Controller name box, type CityController, and then click Add.
- In the CityController.cs code window, locate the following code:
using Microsoft.AspNetCore.Mvc;- Ensure that the cursor is at the end of the Microsoft.AspNetCore.Mvc namespace, press Enter, and then type the following code:
using System.IO;
using Microsoft.AspNetCore.Hosting;
using WorldJourney.Models;- In the CityController class code block, in the Index action code block, locate the following code:
return View();- Place the cursor before the located code, and type the following code:
ViewData["Page"] = "Search city";- In the CityController code window, ensure that the cursor is at the end of the Index action code block, press Enter twice, and then type the following code:
public IActionResult Details()
{
}- In the Details action code block, type the following code:
ViewData["Page"] = "Selected city";
City city = null;
if (city == null)
{
return NotFound();
}
return View(city);- In the CityController code window, ensure that the cursor is at the end of the Details action code block, press Enter twice, and then type the following code:
public IActionResult GetImage()
{
}- In the GetImage action code block, type the following code:
ViewData["Message"] = "display Image";
City requestedCity = null;
if (requestedCity != null)
{
string fullPath = "";
FileStream fileOnDisk = new FileStream(fullPath, FileMode.Open);
byte[] fileBytes;
using (BinaryReader br = new BinaryReader(fileOnDisk))
{
fileBytes = br.ReadBytes((int)fileOnDisk.Length);
}
return File(fileBytes, requestedCity.ImageMimeType);
}
else
{
return NotFound();
}- In the CityController class code block, select the following code:
public IActionResult Details()- Replace the selected code with the following code:
public IActionResult Details(int? id)- In the CityController class code block, select the following code:
public IActionResult GetImage()- Replace the selected code with the following code.:
public IActionResult GetImage(int? cityId)-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, expand Controllers, and then click HomeController.cs.
-
In the HomeController code window, in the Index action code block, select the following code:
return View();- Replace the selected code with the following code:
return RedirectToAction("Index", "City");-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, under Controllers, click CityController.cs.
-
In the CityController class code block, locate the following code:
public IActionResult Index()- Place the mouse cursor before the located code, type the following code, and then press Enter.
private IData _data;
private IHostingEnvironment _environment;
public CityController(IData data, IHostingEnvironment environment)
{
_data = data;
_environment = environment;
_data.CityInitializeData();
}- In the Details action code block, select the following code:
City city = null;- Replace the selected code with the following code:
City city = _data.GetCityById(id);- In the GetImage action code block, select the following code:
City requestedCity = null;- Replace the selected code with the following code:
City requestedCity = _data.GetCityById(cityId);- In the GetImage action code block, select the following code:
string fullPath = "";- Replace the selected code with the following code:
string webRootpath = _environment.WebRootPath;
string folderPath = "\\images\\";
string fullPath = webRootpath + folderPath + requestedCity.ImageName;- In the CityController class code block, in the Details action code block, locate the following code:
return View(city);- Place the mouse cursor before the located code, and type the following code:
ViewBag.Title = city.CityName;-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Save All.
-
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.
-
In Microsoft Edge, on the Earth image, click the London area. Note the red arrow at the center of the Earth image.
Note: The browser displays the Details action result inside the City controller.
-
In Microsoft Edge, click Close.
Results: After completing this exercise, you will be able to create MVC controllers that implement common actions for the City model class in the application.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, right-click the Controllers folder, point to Add, and then select Controller.
-
In the Add Scaffold dialog box, click MVC controller - Empty, and then click Add.
-
In the Add Empty MVC Controller dialog box, in the Controller name box, type TravelerController, and then click Add.
-
In the TravelerController class code block, select the following code:
public IActionResult Index()
{
return View();
}- Replace the selected code with the following code:
public IActionResult Index(string name)
{
ViewBag.VisiterName = name;
return View();
}-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Save All.
-
In the WorldJourney - Microsoft Visual Studio window, on the DEBUG menu, click Start Without Debugging.
-
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.
-
In Microsoft Edge, click Close.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, click Startup.cs.
-
Inside the Configure method code block, in the Startup class, select the following code:
app.UseMvcWithDefaultRoute();- Replace the selected code with the following code:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "TravelerRoute",
template: "{controller}/{action}/{name}",
constraints: new { name = "[A-Za-z ]+" },
defaults: new { controller = "Traveler", action = "Index", name = "Katie Bruce" });
routes.MapRoute(
name: "defaultRoute",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { id = "[0-9]+" });
});Note: You can replace the default name Katie Bruce with your name.
-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Save All.
-
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.
-
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.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, under Controllers, click CityController.cs.
-
In the Index action code block, locate the following code:
public IActionResult Index()- Place the cursor before the located code, press Enter, and then type the following code:
[Route("WorldJourney")]- In the Details action code block, locate the following code:
public IActionResult Details(int? id)- Place the cursor before the located code, press Enter, and then type the following code:
[Route("CityDetails/{id?}")]-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Save All.
-
In the WorldJourney - Microsoft Visual Studio window, on the DEBUG menu, click Start Without Debugging.
-
In Microsoft Edge, right-click the page, and then select View source.
-
In Developer Tools, click Elements.
-
Press Ctrl + B.
-
Place the cursor over the Go Next button, and then click.
Note: In Developer Tools, in the a tag, verify that the href attribute is /WorldJourney.
-
In Developer Tools, click Close.
-
Click Go Next.
Note: Verify that the new route works. 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.
-
In Microsoft Edge, right-click the page, and then select View source.
-
In Developer Tools, click Elements.
-
Press Ctrl + B.
-
Put the cursor over the Earth image and then press Enter.
Note: In the Developer Tools, under the map tag, inside the area tag, verify that the value of href for the London attribute is /CityDetails/2.
-
In Microsoft Edge, on the Earth image, click the London area. Note the red arrow at the center of the Earth image.
Note: Verify that the new route works. 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.
-
In Microsoft Edge, click Close.
Results: After completing this exercise, you can add custom routes to the City controller by using the Route attribute.
-
In Solution Explorer, right-click WorldJourney, point to Add, and then select New Folder.
-
In the NewFolder box, type Filters, and then press Enter.
-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, right-click Filters, point to Add, and then select Class.
-
In the Add New Item – WorldJourney dialog box, in the Name box, type LogActionFilterAttribute, and then click Add.
-
In LogActionFilterAttribute locate the following code:
using System.Threading.Tasks;- Ensure that the cursor is at the end of the using System.Threading.Tasks namespace, press Enter, and then type the following code:
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;- In the LogActionFilterAttribute class code window, locate the following code:
public class LogActionFilterAttribute- Append the following code to the existing line of code:
: ActionFilterAttribute- In the LogActionFilterAttribute class code block, press Enter, and then type the following code:
private IHostingEnvironment _environment;
private string _contentRootPath;
private string _logPath;
private string _fileName;
private string _fullPath;
public LogActionFilterAttribute(IHostingEnvironment environment)
{
_environment = environment;
_contentRootPath = _environment.ContentRootPath;
_logPath = _contentRootPath + "\\LogFile\\";
_fileName = $"log {DateTime.Now.ToString("MM-dd-yyyy-H-mm")}.txt";
_fullPath = _logPath + _fileName;
}- In the LogActionFilterAttribute class code block, ensure that the cursor is at the end of the LogActionFilterAttribute method code block, press Enter twice, and then type the following code:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}- In the OnActionExecuting method code block, press Enter, type the following code, and then press Enter.
Directory.CreateDirectory(_logPath);
string actionName = filterContext.ActionDescriptor.RouteValues["action"];
string controllerName = filterContext.ActionDescriptor.RouteValues["controller"];
using (FileStream fs = new FileStream(_fullPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine($"The action {actionName} in {controllerName} controller started, event fired: OnActionExecuting");
}
}- In the LogActionFilterAttribute class code block, ensure that the cursor is at the end of the OnActionExecuting method code block, press Enter twice, and then type the following code:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}- In the OnActionExecuted method code block, press Enter, type the following code, and then press Enter.
string actionName = filterContext.ActionDescriptor.RouteValues["action"];
string controllerName = filterContext.ActionDescriptor.RouteValues["controller"];
using (FileStream fs = new FileStream(_fullPath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine($"The action {actionName} in {controllerName} controller finished, event fired: OnActionExecuted");
}
}- In the LogActionFilterAttribute class code block, ensure that the cursor is at the end of the OnActionExecuted method code block, press Enter twice, and then type the following code:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}- In the OnResultExecuted method code block, press Enter, type the following code, and then press Enter.
string actionName = filterContext.ActionDescriptor.RouteValues["action"];
string controllerName = filterContext.ActionDescriptor.RouteValues["controller"];
ViewResult result = (ViewResult)filterContext.Result;
using (FileStream fs = new FileStream(_fullPath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine($"The action {actionName} in {controllerName} controller has the following viewData : {result.ViewData.Values.FirstOrDefault()}, event fired: OnResultExecuted");
}
}-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, click Startup.cs.
-
Place the cursor at the end of the using WorldJourney.Models namespace code, press Enter, and then type the following code:
using WorldJourney.Filters;- In the Startup.cs code window, locate the following code:
services.AddSingleton<IData, Data>();- Place the mouse cursor after the located code, type the following code, and then press Enter.
services.AddScoped<LogActionFilterAttribute>();-
In the WorldJourney - Microsoft Visual Studio window, in Solution Explorer, expand Controllers, and then click CityController.cs.
-
In the CityController.cs code block, locate the following code:
using WorldJourney.Models;- Ensure that the cursor is at the end of the using WorldJourney.Models namespace, press Enter, and then type the following code:
using WorldJourney.Filters; - In the CityController class code block, locate the following code:
[Route("WorldJourney")]- Place the mouse cursor before the located code, press Enter, and then type the following code:
[ServiceFilter(typeof(LogActionFilterAttribute))]-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Save All.
-
In the WorldJourney - Microsoft Visual Studio window, on the DEBUG menu, click Start Without Debugging.
-
Click Go Next.
-
In Microsoft Edge, on the Earth image, click the London area. Note the red arrow in the center of the Earth image.
-
Click Go Back.
-
In Microsoft Edge, click Close.
-
In the WorldJourney - Microsoft Visual Studio window, on the FILE menu, click Exit.
-
Navigate to [Repository Root]\Allfiles\Mod04\Labfiles\01_WorldJourney_begin\WorldJourney\LogFile and open Text file.
Note: Text file displays the new filter result.
Results: After completing this exercise, you can create an action filter class that logs the details of actions, controllers, and parameters to external file whenever an action is called.
©2019 Microsoft Corporation. All rights reserved.
The text in this document is available under the Creative Commons Attribution 3.0 License, additional terms may apply. All other content contained in this document (including, without limitation, trademarks, logos, images, etc.) are not included within the Creative Commons license grant. This document does not provide you with any legal rights to any intellectual property in any Microsoft product. You may copy and use this document for your internal, reference purposes.
This document is provided "as-is." Information and views expressed in this document, including URL and other Internet Web site references, may change without notice. You bear the risk of using it. Some examples are for illustration only and are fictitious. No real association is intended or inferred. Microsoft makes no warranties, express or implied, with respect to the information provided here.