c# - Mvc6 路由(RoutePrefix 和 AreaPrefix)

标签 c# asp.net-mvc routing attributerouting

我已经开始考虑将应用程序转移到 MVC6 上以利用新框架。我遇到的最大问题之一是路由(仅限属性路由,我已经完成删除默认路由)。

我的应用程序通常是这样设置的:

区域/管理/ Controller 区域/客户/控制者 /Controllers <- 非区域项目

在每个区域中,我都有一个基本 Controller (例如 AdminBase、CustomerBase),它将包含带有“AreaPrefix”的 [Area] 标签,并且该区域中的每个 Controller 都将继承它并指定一个 [RoutePrefix]。

问题出现了,如果我想在路由中包含区域/ Controller ,每个 ActionResult 必须包含 [Route([area]/[controller]/[action]")] 来生成输出,但是如果,例如我有一个“ChangeAddress” Controller ,我会在 URL 中将它作为“change-address”前缀,但我看不出有什么办法,如果不明确地将它放在 Controller 中的所有路由上如何实现这一点?

最佳答案

在 MVC6 中你仍然有区域和前缀,它只是被降级为 Controller 级别的路由标签,并将 Action 路由放入 http 动词中。所以即

这个:

[RouteArea("AreaPrefix")]
[RoutePrefix("RoutePrefix")]
public class HomeController : Controller
{
    ...
    [HttpGet]
    [Route("LoginAction")]
    public ActionResult Login() ....

成为

[Route("AreaPrefix/ControllerPrefix")]
public class HomeController : Controller
{
    ...
    [HttpGet("LoginAction")]
    public IActionResult Login() {

所以它更加模棱两可,但我个人是 self 牺牲路由过程的罪魁祸首,并且它使用 [] 表示法中的标准路由对象(将其视为之前的 {})。但它仍然提供了一次指定分层并完成的控制级别,因此它现在提供了一个更简单的继承模型:

[Route("AreaPrefix/ControllerPrefix")
public class HomeOps : Controller // Controller Suffix is optional
{

}

[Route("api")]
public class HomeApiOps : HomeOps
{
     // put the api AJAX methods here
     [HttpPost("lookup")] // will route to // AreaPrefix/ControllerPrefix/api/lookup
     public IActionResult Lookup() {
}

public class HomePageOps : HomeOps
{
     // put similar routes for View returns, file content responses here
     [HttpPost("lookup")] // Will route to AreaPrefix/ControllerPrefix/lookup
     public IActionResult Lookup() {

}

这可以深入到一种更有条理的方式来表达“工作单元”和 “业务线”概念,您可以在其中轻松分组和分离 api 调用和页面,而无需庞大的 Controller 或无休止的#region trip ups。

通过这种继承,还请记住,您可以为每个区域创建一个根 Controller 类,并为区域范围分层设置某些路由,然后继承到第二层以获取“ControllerPrefix”开销路由,并且只需要在每个操作上指定action 路由名称,它使用继承汇总将路由粘合在一起,将前面的示例变成 AreaPrefix/ControllerPrefix/Route

我和你一起使用 MVC6,我公司的客户端开发人员喜欢这个平台,在数据端,它让他们的信息变得干净简单,但稀疏的文档有时会令人沮丧...希望这有帮助

关于c# - Mvc6 路由(RoutePrefix 和 AreaPrefix),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521618/

相关文章:

c# - Linq查询以获取两个日期之间的所有值

asp.net-mvc-2 - ASP.NET MVC 2参数数组

php - Symfony2 包继承丢失父包路由

c# - 使用 Blazor 和 C# 刷新 html 表格数据

asp.net-mvc - 禁用向访问网站的用户发出 "Remember My Password"提示

asp.net-mvc - 无法到达 Visual Studio 调试 "This site can'”

templates - 样式表不适用于使用 chi 路由器的 go html 模板

c# - 在构建 POCO 或简单的 DTO 时,我可以使用结构而不是类吗?

c# - 如何添加资源 : xml file

c# - 如何从 aspx 引用 cs 中的常量?