在应用程序中创建一个新的Area,在应用程序的根目录下创建一个Areas文件夹命名为Sales,现在在Areas文件夹内创建Controllers、Modes、Views,如下面例子所示:

在应用程序的Pragram.cs类添加一个Area路由,下面代码:
app.MapControllerRoute(name: "areas",pattern: "{area:exists}/{controller=Home}/{action=Index}");
3 Sales Area创建Model、View、Controller
namespace AspNetCore.Areas.Areas.Sales.Models{public class Product{public string Name { get; set; }public int Quantity { get; set; }public int Price { get; set; }}}
接下来创建一个新的controller在Areas->Sales->Controllers文件夹下, 命名为HomeController.cs,添加下面代码:
using AspNetCore.Areas.Areas.Sales.Models;using Microsoft.AspNetCore.Mvc;namespace AspNetCore.Areas.Areas.Sales.Controllers{[Area("Sales")]public class HomeController : Controller{public IActionResult Index(){Product[] productArray = new Product[] {new Product { Name = "Pants", Quantity = 5, Price=100 },new Product { Name = "Shirts", Quantity = 10, Price=80 },new Product { Name = "Shoes", Quantity = 15, Price=50 }};return View(productArray);}}}
ASP.NET Core 帮助标签在Areas不工作, 我们必须在Areas内Razor View Imports文件内注册帮助标签,否则帮助标签不工作,在Areas->Sales->Views文件夹下创建_ViewImports.cshtml并且注册帮助标签
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers最后一部分在Areas->Sales->Views->Home文件夹下添加Index视图,内容如下:
@using AspNetCore.Areas.Areas.Sales.Models@model Product[]@{Layout = null;}<!DOCTYPE html><html><head><title>Routing</title></head><body><table><tr><th>Name</th><th>Quantity</th><th>Price</th></tr>@foreach (Product p in Model){<tr><td>@p.Name</td><td>@p.Quantity</td><td>@p.Price</td></tr>}</table></body></html>
这个视图将在HTML表格中显示所有产品,运行应用程序,我们将看到Sales Area的HomeController的Action方法被调用并且产品显示在浏览器上

<a asp-action="List">Link1</a>将会生成如下链接:
<a href="/Sales/Home/List">Link1</a>
<a asp-action="List" asp-controller="Report">Link</a>将会生成如下链接:
<a href="/Sales/Report/List">Link</a>我们使用相同的步骤-在Areas文件夹下创建一个新的文件夹叫Employee,接下来在Employee文件夹下创建Controllers,Modesl,Views
Area->Employee->Controllers文件夹下添加HomeController使用下面代码:
using Microsoft.AspNetCore.Mvc;namespace AspNetCore.Areas.Areas.Employee.Controllers{[Area("Employee")]public class HomeController : Controller{public IActionResult Index(){return View();}}}
修改Areas->Sales->Views->Home下的Index视图,创建一个链接使用asp-area帮助标签
<a asp-action="List" asp-controller="Home" asp-area="Employee">Link3</a>你将会发现生成如下链接:
<a href="/Employee/Home/List">Link3</a>6 从Area链接到应用程序主体目录
<a asp-action="List" asp-controller="Home" asp-area="">Link3</a>将生成下面链接:
<a href="/Home/List">Link4</a>总结
这节我们讲解了ASP.NET Core中Areas和路由的特性,以及使用它来创建URL
源代码地址