asp.net mvc 把控制器放到一个单独的项目中 [英] asp.net mvc put controllers into a separate project

查看:35
本文介绍了asp.net mvc 把控制器放到一个单独的项目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 asp.net mvc,我正在尝试弄清楚如何将我的控制器移动到一个单独的项目中.通常,当我之前设计 asp.net Web 应用程序时,我为我的模型创建了一个项目,为我的逻辑创建了另一个项目,然后是 Web.

I'm just learning asp.net mvc and I'm trying to figure out how to move my controllers into a separate project. Typically when I have designed asp.net web apps before, I created one project for my models, another for my logic, and then there was the web.

现在我正在学习 asp.net mvc,我希望遵循类似的模式,将模型和控制器分别放入自己单独的项目中,而将视图/脚本/css 留在网络中.模型部分很简单,但我不明白的是如何在单独的项目中找到"我的控制器.另外,我想知道这是否可取.谢谢!

Now that I'm learning asp.net mvc I was hoping to follow a similar pattern and put the models and controllers each into their own separate projects, and just leave the views/scripts/css in the web. The models part was easy, but what I don't understand is how to make my controllers in a separate project be "found". Also, I would like to know if this is advisable. Thanks!

推荐答案

首先,将您的模型放到一个单独的项目中当然是个好主意.正如您所发现的,这是微不足道的.

First of all, it is certainly a good idea to put your model into a separate project. As you've discovered, this is trivial.

关于控制器和视图,对于大多数基本项目,我认为将它们分开没有任何明显的优势,尽管您可能在特定应用程序中特别需要这样做.

Regarding Controllers and Views, I don't see any obvious advantage to separating them for most basic projects, although you may have a particular need to do so in a particular application.

如果你选择这样做,那么你需要告诉框架如何找到你的控制器.执行此操作的基本方法是提供您自己的 ControllerFactory.您可以查看 DefaultControllerFactory 的源代码以了解这是如何完成的.对此类进行子类型化并覆盖 GetControllerType(string controllerName) 方法可能足以完成您的要求.

If you do choose to do this, then you will need to tell the framework how to find your controllers. The basic way to do this is by supplying your own ControllerFactory. You can take a look at the source code for the DefaultControllerFactory to get an idea for how this is done. Subtyping this class and overriding the GetControllerType(string controllerName) method may be enough to accomplish what you're asking.

创建自己的自定义 ControllerFactory 后,将以下行添加到 global.asax 中的 Application_Start 以告诉框架在哪里可以找到它:

Once you've created your own custom ControllerFactory, you add the following line to Application_Start in global.asax to tell the framework where to find it:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());

更新:阅读这篇文章 文章它链接到以获取更多信息.另请参阅 Phil Haack 对该帖子的评论:

Update: Read this post and the posts it links to for more info. See also Phil Haack's comment on that post about:

ControllerBuilder.Current.DefaultNamespaces.Add(
    "ExternalAssembly.Controllers");

...这不是一个完整的解决方案,但对于简单的情况可能已经足够了.

...which is not a complete solution, but possibly good enough for simple cases.

这篇关于asp.net mvc 把控制器放到一个单独的项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆