【问题标题】:Controller throwing "Need parameterless constructor" error when I clearly have one当我明显有一个控制器时,控制器抛出“需要无参数构造函数”错误
【发布时间】:2013-11-25 21:38:25
【问题描述】:

我最近刚刚将我的项目从 VS2010 和 .NET 4.0 升级到 VS2013 和 .NET 4.5.1

在修复了大多数包的许多其他程序集引用和依赖问题后,我无法让我的控制器继续工作。这是我得到的堆栈跟踪错误:

ExceptionMessage=An error occurred when trying to create a controller of type 'ExamplesController'. Make sure that the controller has a parameterless public constructor. 

根据我在其他地方读到的内容,这是一个常见问题,尽管在升级到 .NET 4.5.1 和 Web Api 2 之前,我的任何构造函数中都不需要无参数构造函数。

这是我将控制器更改为:

 public class ExamplesController : ApiController
{

    static readonly IVehicleRepository repository = new ExampleRepository();

    public ExamplesController() {}

    // GET api/v1/examples
    public HttpResponseMessage GetExamples()

    //etc etc

但当我尝试在此控制器上进行测试时,我仍然遇到上述错误。

这里还可能发生什么。我的 Web.config 中有什么东西?

谢谢。

编辑:

这是与我的 Response 标头中最重要的错误一起出现的 StackTrace:

StackTrace=  at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()

编辑2: 当我尝试构建项目时,这会出现在我的错误列表中:

Warning 2   Found conflicts between different versions of the same dependent assembly that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed. TrackStarServices
Error   1   'System.Web.Http.GlobalConfiguration' does not contain a definition for 'Configure' C:\Projects\AVLS-Web-Services\TrackStarServices\Global.asax.cs  21  33  TrackStarServices

如果有人想查看它的任何部分,我有构建日志(它很大)。

好的,在修复引用并重新安装包之后,我认为主要的罪魁祸首是 EntityFramework 的目标是 6.0.0.1 版本而不是 6.0.0.0。

只是将其更改为引用顶级版本,现在所有控制器都可以正常工作。浪费一天。谢谢大家。

【问题讨论】:

  • 您是否使用任何类型的依赖注入或 IoC 容器?
  • 如果你没有任何其他构造函数,拥有 public ExamplesController() {} 应该与没有任何东西是一样的。
  • 无依赖注入或 IoC 容器
  • @Clamidity true,但为了示例代码,最好澄清一下,是的,它就在那里,是的,它是公开的。
  • @TimS。这是有道理的。

标签: c# asp.net asp.net-web-api .net-4.5


【解决方案1】:

我在升级时遇到了类似的问题。它通常被证明是我的 Web.Config 文件中程序集的混合版本。

试试这个链接:http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

可能不是同一次升级,但它显示了在哪里查找错误。

【讨论】:

  • 谢谢。这些都是我需要做的升级。但是在尝试调用该控制器或任何控制器时,我仍然遇到同样的错误。
  • 我遇到了同样的问题。一切似乎都已正确设置,但 Web API 2 AutoFac 集成似乎有些不稳定。
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多