ASP.NET MVC 控制器命名多元化

问题描述 投票:0回答:4

RESTful 约定表明在单数对象上使用复数名词。

命名 ASP.NET MVC 控制器的复数约定是什么,即

ProductController
还是
ProductsController

asp.net-mvc naming-conventions pluralize asp.net-mvc-controller
4个回答
213
投票

我将不得不不同意之前使用复数或单数并保持一致的答案。每个控制器都应该根据它们是与单个实体还是多个实体交互来使用不同的约定。特别是因为在 URL 中默认使用控制器名称。

虽然项目模板使用单数(HomeController、AccountController),但只有一个 Home,Account 操作仅在会话的单个帐户上运行。我不希望 /homes 的 URL 访问主页,也不希望去 /accounts 来管理我的帐户设置。

复数 HomesController 用于具有与列出和搜索多个房屋相关的方法的房地产网站:/homes/new-listings。


53
投票

一些 MVC 框架使用复数,但是 MVC 项目模板包含一个名为 AccountController 的控制器,因此建议使用单数命名。

没关系。与 Asp.net MVC 框架中的大多数内容一样,选择权在您手中。没有真正的约定。

这是我个人的意见,但重要的是你选择一个方案并保持一致!


13
投票

当您使用 MVC 脚手架为 Entity Framework 实体添加控制器时,VS2013 使控制器名称变为复数,因此我建议使用默认值,使实体的控制器成为复数。

更新:我改变了主意。 LouD 是正确的。这取决于控制器的上下文。


0
投票

它确实取决于控制器的上下文,RESTful API 非常适合这种格式:

GET     Account        gets all accounts
GET     Account/id     gets the account for the specified id
POST    Account        creates an account
PATCH   Account/id     updates an account for the specified id
DELETE  Account/id     deletes an account for the specified id

在大多数情况下,它的单数或复数似乎并不重要,因为动词和

id
告诉你发生了什么......除了POST......我觉得
POST  Accounts
是如此轻微误导,因为它可能会创建多个帐户。

经过多年的尝试,我更喜欢默认的单数形式。我用过

Account
Accounts
- 这些账户实际上是用于批处理操作的,所以我最终得到:

GET     Account        gets all accounts
GET     Account/id     gets the account for the specified id
POST    Account        creates an account
PATCH   Account/id     updates an account for the specified id
DELETE  Account/id     deletes an account for the specified id

POST    Accounts       creates multiple accounts as per POST body
© www.soinside.com 2019 - 2024. All rights reserved.