ASP.NET MVC 路由与特定操作

ASP.NET MVC Routing vs Specific Actions

我对用什么方法来完成事情有点困惑。我的网站可以向用户显示故事提要,并且提要可以是多个类别之一。 (例如,您可以查看 "All Stories" 提要或 "My Submissions" 提要)。

在处理路由方面,以下是否更有意义:

1) 让一个动作 (Home/index) 处理不同的 "storyCategory" 路由参数,如下所示:

[Route("~/"), Route("")] //Index will be default route for both SiteRoot and SiteRoot/Home
[Route("{storyCategory?}/{page?}")]
[Route("{storyCategory?}/Page/{page?}")]
public ActionResult Index(Story.Category storyCategory = Story.Category.None, int page = 1)

2) 对每个故事类别都有特定的操作,而不是将枚举作为参数传入:

[Route("~/"), Route("")] //Index will be default route for both SiteRoot and SiteRoot/Home
public ActionResult Index(int page = 1) 
public ActionResult ReadLater(int page = 1) 
public ActionResult PlanToUse(int page = 1)

我会选择第一个选项,因为仅仅为了过滤而执行不同的操作毫无意义 articles/content。

在路由中使用枚举似乎也不是完美的选择。有意义的字符串更好。

如果您的所有 Feed 都完全一样,只有几个参数始终相同的操作,那么第一个选项似乎很明显...

但是,如果将来您想在其中一个供稿中使用不同的 "ReadLater"(具有不同的参数),您可能会后悔选择了第一个选项。

出于以下原因,我会选择第二个选项:

  • 行动灵活;
  • URL 由操作名称定义(未硬编码在您的 "index" 操作之上);
  • 可以根据控制器的上下文轻松调整参数;
  • 代码的可读性和可维护性。

此外,如果您的提要增长超过您的预期,您可以创建一个 constants 文件,您可以在其中以这种方式关联每个控制器及其操作:

namespace Stories
{
    public class ControllersNames {
        public const string AllStories = "AllStories";
        public const string MySubmissions = "MySubmissions";
    }

    public class ActionsNames
    {
        #region AllStories
        public const string AllStories_ReadLater = "ReadLater";
        public const string AllStories_PlanToUse = "PlanToUse";
        #endregion

        #region MySubmissions
        public const string MySubmissions_ReadLater = "ReadLater";
        public const string MySubmissions_PlanToUse = "PlanToUse";
        //same action but with different paramaters below
        public const string MySubmissions_PlanToReUse = "PlanToUse"; 
        public const string MySubmissions_Store = "Store";
        #endregion
    }
}

在您看来的某个地方,您可能会遇到类似这样的调用:

<a ... href="@Url.Action(
      ActionsNames.MySubmissions_PlanToUse,
      ControllersNames.MySubmissions,
      new { page = Model.MySubmissions.IDPage })">

更容易阅读和跟进更多操作...