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

本文关键字:控制器 参数 构造函数 确保 创建 错误 | 更新日期: 2023-09-27 17:50:01

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

尝试创建类型为"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
    }
}

正如你所看到的,我没有使用任何形式的依赖注入(因为这是一个小型的非必要的web应用程序),而且我在研究时看到的几乎所有解决方案都涉及到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)"}}}}}
谁能告诉我是什么问题?

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

谁能告诉我是什么问题?
肯定

尝试创建类型为"TimelineController"的控制器时发生错误。

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

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

这只是一个有用的信息,因为大多数情况下,对于非依赖注入的控制器来说,这就是问题所在。

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

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

你可以简单地把它们注释掉,它应该"工作"创建控制器。显然,方法调用将中断,但这将证明其中一个是问题所在。如果让我猜的话,我会说TimelineEventRepository()是罪魁祸首。每个人都造成了这个问题,你应该能够在Visual Studio中调试它。