尝试创建控制器时发生错误,请确保控制器具有无参数的公共构造函数

时间:2015-05-19 14:38:25

标签: c# asp.net-mvc azure asp.net-web-api

在控制器上调用特定方法时,我在不一致的基础上得到以下错误:

  

尝试创建类型为' TimelineController'的控制器时发生错误。确保控制器具有无参数的公共构造函数。

令人困惑的部分是这个方法偶尔会起作用,并且控制器本身确实有一个无参数构造函数。这是代码的简短示例:

[Authorize]
[RoutePrefix("api/timeline")]
public class TimelineController : CherishApiController
{
    private readonly TimelineEventRepository _timelineEventRepository;
    private readonly BlobHelper _blobHelper;
    private readonly ChildHelper _childHelper;
    private readonly AccountHelper _accountHelper;

    public TimelineController()
    {
        _timelineEventRepository = new TimelineEventRepository();
        _blobHelper = new BlobHelper();
        _childHelper = new ChildHelper();
        _accountHelper = new AccountHelper();
    }

    [HttpPost]
    [Route("UploadImage")]
    [ResponseType(typeof(UploadMediaResponse))]
    public async Task<HttpResponseMessage> UploadImage()
    {
        try
        {
            return await Upload(Request.Content, MediaType.Image);
        }
        catch (Exception ex)
        {
            return ErrorResponse(ex);
        }
    }

    private async Task<HttpResponseMessage> Upload(HttpContent requestContent, string mediaType)
    {
        // reads the data from the multi-part request and stores a record in an Azure DocumentDB
    }
}

正如您所看到的,我没有使用任何形式的依赖注入(因为这是一个非必要的小型网络应用程序)以及我在研究涉及的所有解决方案DI设置问题。

如果它有帮助,这是完整的堆栈跟踪:

An error occurred when trying to create a controller of type 'TimelineController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":"  
   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n  
   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"One or more errors occurred.","ExceptionType":"System.AggregateException","StackTrace":"
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)\r\n
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)\r\n
   at System.Threading.Tasks.Task`1.get_Result()\r\n
   at Microsoft.Azure.Documents.Linq.DocumentQuery`1.GetEnumerator()\r\n
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)\r\n
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n
   at Cherish.Domain.Repositories.Implementation.DocumentRepository`1.ReadOrCreateDatabase()\r\n
   at Cherish.Domain.Repositories.Implementation.DocumentRepository`1..ctor()\r\n
   at lambda_method(Closure )\r\n
   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"An error occurred while sending the request.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":"
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
   at Microsoft.Azure.Documents.Linq.DocumentQueryExecutionContext.<ExecuteAllAsync>d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
   at Microsoft.Azure.Documents.Linq.DocumentQuery`1.<GetEnumeratorTAsync>d__10.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Unable to connect to the remote server","ExceptionType":"System.Net.WebException","StackTrace":"
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"An attempt was made to access a socket in a way forbidden by its access permissions","ExceptionType":"System.Net.Sockets.SocketException","StackTrace":"
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)\r\n
   at System.Net.Sockets.Socket.InternalBind(EndPoint localEP)\r\n
   at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)\r\n
   at System.Net.Sockets.Socket.UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)\r\n
   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)"}}}}}

任何人都可以指导我这个问题是什么吗?

1 个答案:

答案 0 :(得分:2)

  

任何人都可以指导我这个问题是什么吗?

不确定

  

尝试创建&#39; TimelineController&#39;类型的控制器时发生错误。

这是实际错误。 ControllerFactory无法创建控制器。

  

确保控制器具有无参数的公共构造函数。

这只是一个有用的信息,因为非依赖注入控制器的大部分时间都是这个问题。

构造函数创建了4个对象(看起来像使用依赖注入的好例子)。

_timelineEventRepository = new TimelineEventRepository();
_blobHelper = new BlobHelper();
_childHelper = new ChildHelper();
_accountHelper = new AccountHelper();

你可以简单地对它们进行评论,它应该&#34;工作&#34;创建控制器。显然方法调用会中断,但这将证明其中一个是问题。如果我猜,我会说TimelineEventRepository()是罪魁祸首。哪个问题导致问题,您应该能够在Visual Studio中调试它。