如何在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/配置方法中:
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):
现在我们在名为AdminController
的Controllers
文件夹内创建一个控制器,内容如下:
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:
现在,你应该很好!
问题: 如果我要在我的区域内放置另一个控制器怎么办?
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屋!