【问题标题】:How to fix `Unable to cast Controller as Controller Type error` - ApiController issues如何修复“无法将控制器转换为控制器类型错误” - ApiController 问题
【发布时间】:2019-06-05 19:26:11
【问题描述】:

我正在创建一个 .net 核心 Angular 网站并遇到 ApiController 的问题,其中 ApiController(按字母顺序 asc 排序)将运行但所有其他人将失败并出现 500 错误,声称以下内容:

InvalidCastException: Unable to cast object of type 'AbcController' to type 'AccController'.

lambda_method(Closure , object , object[] )

使用 Angular 和 ninject(主要相关部分)创建 .net core 2.2 网站。我已将其设置为与 ApiController 工作的现有项目相同,但出现 500 个错误。我尝试在以下之间进行更改:

  • 同时设置为控制器
  • 将两者都设置为 ControllerBase
  • 创建一个在 BaseController 是 Controller 的地方都扩展的 BaseController
  • 创建一个在 BaseController 是 ControllerBase 的地方都扩展的 BaseController
  • 为控制器中的 ApiController 添加/删除标签
  • 为控制器中的路由添加/删除标签
  • 添加/删除了 MVC 路径的手动设置
  • 重新排序的应用程序。### 配置选项,例如 UseStaticFiles() 和 UseMvc()

~控制器1~


    [Route("api/[controller]")]
    [ApiController]
    public class AbcController : ControllerBase
    {
        [HttpGet("Get")]
        public IActionResult Get()
        {
            return this.Ok("ABC hello world");
        }
    }

~控制器2~


    [Route("api/[controller]")]
    [ApiController]
    public class AccController : ControllerBase
    {
        [HttpGet("Get")]
        public IActionResult Get()
        {
            return this.Ok("ACC hello world");
        }
    }

启动配置方法


    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        Kernel = RegisterApplicationComponents(app, loggerFactory);

        app.Use(async (context, next) => { await next.Invoke(); });
        app.UseHttpsRedirection();
        app.UseSession();
        app.UseMvc();
        app.UseHttpMiddleware();
        app.UseDefaultFiles();
        app.UseStaticFiles();
    }

当前结果,尝试调用api/Abc/Get 是有效响应,200 结果。 当前结果,尝试调用 api/Acc/Get 为 500,并带有完整的错误消息:

An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'AbcController' to type 'AccController'.

【问题讨论】:

  • 如果我删除RegisterApplicationComponentsapp.UseHttpMiddleware. Are these custom methods you've written? Can you add them to your question, along with ConfigureServices`,运行它没有问题?

标签: c# angular asp.net-core ninject .net-core-2.2


【解决方案1】:

https://stackoverflow.com/users/2309376/simply-ged 提示我检查 2 个额外的方法,并重新检查了一些旧代码。看起来ninject引起了问题。如上所述,它只是映射一些控制器。我已经删除了 ninject,转而纯粹使用

    services.AddSingleton<ITestService, TestService>();

这已经解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多