asp.net-mvc - Controller 未从不同的程序集加载?

标签 asp.net-mvc routes controller assemblies

我正在尝试从不同的程序集中加载Controller,但我被困在这里。

我有两个项目:

  1. 网络应用程序
  2. 类库

在网络应用程序中,我定义了一个路线:

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/

相关文章:

c# - 如何更新模型状态?

java - Spring 3 AJAX POST 请求与@RequestBody 和@ModelAttribute 以及@SessionAttribute 一起使用?

c# - ASP.Net MVC 中的演练屏幕

angularjs - 使用 ASP.NET MVC 6 和 AngularJS 在 SPA 中进行路由

routes - 为什么 Blazor WASM 路由部署在服务器上后不使用正确的基本 URI? (NavigationManager.NavigateTo() 方法)

python - 使用路由中的正则表达式替换重写 URL

javascript - $scope 变量发生变化时未触发 Angular $watch

asp.net-mvc - MVC、ViewModels、BLL、自上而下的交互

c# - 试图避免服务器上的流量

c# - 使用 Azure 存储存储媒体文件