Is like to have all files in the same directory or keep files separated in different folders.
Keeping the application organized in separate controller help in many cases:
1)内存性能
Different from Java Servlet where the controller is shared betwen many request, in asp net mvc the controller is created for each request.
Each time the user make a request, the application need to create the controller.
Think at performances comparison betwen create in memory an instance of a fatcontroller of 100k VS one instance of a light controller of 1k.
2)OO好处
Controllers are classes. Each time you create a new controller you extend the base controller.
In a complex application you can create yours own controrres (can be more than one) and extend the more appropriated.
例如,您可以为“产品”创建一个控制器,并从中扩展到为“蔬菜产品”创建控制器,等等。。
3)安全性
Suppose that in your application you have a page that execute the CRUD actions on a given item of your db:
- display
- edit
- update
- delete
您想使此页面仅为注册用户保留。
If you put all this method in one separate controller you can put the annotation [Authorize] on the controller and by default all the methods inside the controller will be protected.
If you put all the application in one fat controller you have to be careful to place the [Authorize] on each method (what happe if you forgive to put the annotation on the delete method?)
[Authorize]
public class ProductController
public ActionResult Index(String id) {
...
}
public ActionResult Update(String id) {
...
}
public ActionResult Delete(String id) {
...
}
4)再次安全
Suppose you write a classic CRUD (Create Read Update Delete).
Now you want to delete the whole CRUD.
If you keep code separate in different controller you simply delete the controller that belog the CRUD.
If you keep all together in a fatcontroller you have to search for the methods that belog to the CRUD in the whole code.
Again: what hapen if you forget to delete the Delete method?
实用性
如果你把所有这些放在一起,你会有这样的方法:
product_edit
product_delete
product_rate
product_create
category_edit
category_delete
category_create
如果您在单独的控制器中组织代码,您将拥有
product
edit
delte
create
rate
category
edit
delete
create
这是好的,原因有很多:想修改项目中的产品吗?只需重构并重命名itemController中的productController。