我正在尝试从不同的程序集中加载Controller
,但我被困在这里。
我有两个项目:
- 网络应用程序
- 类库
在网络应用程序中,我定义了一个路线
:
routes.MapRoute("Root", "root/{Action}",
new {Controller = "Root", Action = "Index" });
现在,当我点击以下 URL 时,路由会匹配,但会抛出 404 错误。 有人能告诉我为什么会发生这种情况吗?(p.s. RootController
位于类库中)
http://webapp/root
我尝试添加自定义 Controller 工厂:
public class ControllerFactory : DefaultControllerFactory {
protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
{
// reqContext.Route is correct and has the "Root" route loaded
// controllerType seems to be null ??
// if I break execution here and manually set controllerType to
// typeof(ClassLibrary.RootController) and continue from there,
// then everything works as expected...
// So this method is being called without controllerType... but why??
}
}
我还尝试向路由添加 namespaces
属性:
routes.MapRoute("Root", "root/{Action}",
new {
Controller = "Root",
Action = "Index",
Namespaces = new[] { typeof(RootController).Namespace }
});
最佳答案
经过多次调试和挫折后,我发现 Controller 类被声明为 private
,这在该场景中不起作用。
即使我的 ControllerFactory
位于同一命名空间中,但创建 Controller 缓存的类却不在同一命名空间中。因此,由 DefaultControllerFactory
基类发出的对 GetControllerInstance
的请求无法找到 RootController
类。
将 RootController
声明为 public
可以解决该问题。
关于asp.net-mvc - Controller 未从不同的程序集加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9861744/