如何在 ASP.NET Core 中使用区域 [英] How to use an Area in ASP.NET Core
问题描述
如何在 ASP.NET Core 中使用 Area
?
How do I use an Area
in ASP.NET Core?
我有一个需要管理部分的应用.此部分要求将其视图放置在该区域中.所有以 Admin/
开头的请求都需要重定向到该区域.
I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/
will need to be redirected to that area.
推荐答案
为了在 ASP.NET Core 应用程序中包含一个区域,首先我们需要在 Startup.cs
文件(最好放在任何非区域路由之前):
In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the Startup.cs
file (It's best to place it before any non-area route):
在 Startup.cs/Configure 方法中:
In Startup.cs/Configure method:
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
然后在应用根目录下创建一个名为Areas
的文件夹,在前者里面再创建一个名为Admin
的文件夹,同样在Admin
内创建这些文件夹(ViewComponent 是可选的):
Then make a folder named Areas
in the app root and make another named Admin
inside the former, also make these folders inside Admin
(ViewComponent is optional):
现在我们在Controllers
文件夹中创建一个名为AdminController
的控制器,内容可以是:
Now we create a controller inside the Controllers
folder named AdminController
, the content can be like:
[Area("Admin")]
[Route("admin")]
public class AdminController : Controller
{
public AdminController()
{
// do stuff
}
public IActionResult Index()
{
return View();
}
[Route("[action]/{page:int?}")]
public IActionResult Orders()
{
return View();
}
[Route("[action]")]
public IActionResult Shop()
{
return View();
}
[Route("[action]/newest")]
public IActionResult Payments()
{
return View();
}
}
现在为了让它起作用,您需要为所有返回一个的操作创建视图.视图的层次结构就像您在非区域视图文件夹中所拥有的一样:
Now in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for views is just like what you have in a non-area Views folder:
现在,您应该可以出发了!
Now, you should be good to go!
问题:如果我的区域内有另一个控制器怎么办?
Question: What if I what to have another controller inside my Area?
答案:
只需在 AdminController
旁边添加另一个控制器并确保路由如下所示:
Just add another controller beside AdminController
and make sure the routes are like the following:
[Area("Admin")]
[Route("admin/[controller]")]
public class ProductsController : Controller
{
public ProductsController()
{
//
}
[Route("{page:int?}")]
public IActionResult Index()
{
return View();
}
}
重要的部分是[Route("admin/[controller]")]
.这样你就可以保持路由到 admin/controller/action/...
The important part is [Route("admin/[controller]")]
. With that you can keep the style of routing to admin/controller/action/...
这篇关于如何在 ASP.NET Core 中使用区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!