Postman call does not enter the controller constructor with parameter

Asked

Viewed 106 times

-2

I took a project already developed, but with several problems. In the controller that I am working on, I put a break in the constructor with a parameter and does not enter. If I define one without parameter and keep the other(with parameter), break stops in no without parameter and not in with parameter. The scenario looked like this: 1) The injection was being made by an object and not an interface, as is common. Is it possible to inject an object? My testing solution was: I commented on everything, created an interface with a method, in the Budget class, and injected it into the controller’s constructor, but that didn’t work either. See the controller as it is:

[ApiVersion("1")]
    [RoutePrefix("orders")]
    [Description("doc0x03303001")]
    public class OrdersController : ApiController
    {
        private readonly OrdersManager _mng;

        //public OrdersController(){}

        public OrdersController(OrdersManager mng)
        {
            if (mng == null)
                throw new ArgumentNullException(nameof(mng));

            _mng = mng;
        }

        [HttpGet]
        public IHttpActionResult GetTeste()
        {
            _mng.ReceiveAssessment("ok", "ok", "ok", 1);
            return Ok("");
        }
    }

The Receiveassessment method is this(only to test whether or not you enter the method)

public void ReceiveAssessment(string assessment, string claimNumber, string registerNumber, int code)
        {
            string _assessment = assessment;
            string _claimnumber = claimNumber;
            string _registernumber = registerNumber;
            int _code = code;
        }

below the Ordersmanager

public class OrdersManager : IDisposable, IOrdersManager
    {

        private OrdersManagement _mng;
        private OrderDist _orderDist;
        private SystemAssessment _systemAssessment;
        private BlackListSupplier _blacklistsuplier;

        public OrdersManager(string idUser, string login, string timezone,
            string idCompany, string idCompanyType)
        {
            _mng = new OrdersManagement(idUser, login, timezone, idCompany, idCompanyType);
        }


        public void ReceiveAssessment(string assessment, string claimNumber, string registerNumber, int code)
        {
            string _assessment = assessment;
            string _claimnumber = claimNumber;
            string _registernumber = registerNumber;
            int _code = code;


        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                //TODO: SSO
                //_mng?.Dispose();
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }

        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        ~OrdersManager()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(false);
        }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            // TODO: uncomment the following line if the finalizer is overridden above.
            GC.SuppressFinalize(this);
        }
        #endregion
    }

Ordersmanager is an object, as I reported above. How do I enter the controller and continue running the API?

The errors are concatenated in a class (an array of errors) and below I put them, taken in the settings passed above, and I call the Getteste action and do not receiveassessment.

{ "message": "An error has occurred.",

"exceptionMessage": "The specified API version is invalid.",

"exceptionType": "System.FormatException",

"stackTrace": "   at Microsoft.Web.Http.ApiVersion.Parse(String text)\r\n   at

System.Linq.Enumerable.Whereselectarrayiterator2.MoveNext()\r\n at System.Linq.Enumerable.<DistinctIterator>d__641.Movenext() r n at System.Linq.Buffer1..ctor(IEnumerable1 source) r n at System.Linq.Enumerable.Toarray[Tsource](Ienumerable1 source)\r\n at Microsoft.Web.Http.CollectionExtensions.ToSortedReadOnlyList[T](IEnumerable1 Quence) r n at Microsoft.Web.Http.Versioning.Apiversionsbaseattribute.<>c__DisplayClass5_0. <. ctor>b__1() r n At System.Lazy1.CreateValue()\r\n at System.Lazy1.Lazyinitvalue() r n at System.Lazy1.get_Value()\r\n
at Microsoft.Web.Http.Versioning.ApiVersionsBaseAttribute.get_Versions()\r\n at System.Web.Http.AttributeExtensions.<>c__0
1.b__0_1(T attribute) r n at System.Linq.Enumerable.d__233.MoveNext()\r\n at System.Linq.Buffer1.ctor (Ienumerable1 source)\r\n at System.Linq.OrderedEnumerable1.d__1.Movenext() r n
at System.Linq.Enumerable.Whereselectenumerableiterator2.MoveNext()\r\n at System.Linq.Enumerable.<DistinctIterator>d__641.Movenext() r n
At System.Linq.Buffer1..ctor(IEnumerable1 source) r n at System.Linq.Enumerable.Toarray[Tsource](Ienumerable1 source)\r\n at System.Web.Http.AttributeExtensions.GetImplementedApiVersions[T](IEnumerable1 Attributes) r n at Microsoft.Web.Http.Versioning.Apiversionmodel.Getdeclaredcontrollerapiversions(Httpcontrollerdescriptor controllerDescriptor) r n at Microsoft.Web.Http.Versioning.Apiversionmodel.<>c__DisplayClass1_0. <. ctor>b__0() r n At System.Lazy1.CreateValue()\r\n at System.Lazy1.Lazyinitvalue() r n at System.Lazy1.get_Value()\r\n
at Microsoft.Web.Http.Versioning.ApiVersionModelExtensions.Aggregate(ApiVersionModel version, IEnumerable
1 otherVersions) r n at System.Web.Http.HttpControllerDescriptorExtensions.Aggregateversions(Ienumerable1 controllerDescriptors)\r\n at Microsoft.Web.Http.Dispatcher.ApiVersionControllerAggregator.AggregateAllCandiateVersions()\r\n at System.Lazy1.Createvalue() r n at System Lazy.1.LazyInitValue()\r\n at System.Lazy1.get_Value() r n
at Microsoft.Web.Http.Dispatcher.Conventionroutecontrollerselector.Selectcontroller(Apiversioncontrolleraggregator Aggregator) r n at Microsoft.Web.Http.Dispatcher.Apiversioncontrollerselector.Selectcontroller(Httprequestmessage request) r n at System.Web.Http.Dispatcher.Httpcontrollerdispatcher.d__15.Movenext()" }

When the compiler skips the constructor with parameters, it falls here first:

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var responseMessage = await base.SendAsync(request, cancellationToken);

            object contentVal;
            if (!responseMessage.TryGetContentValue(out contentVal))
                return responseMessage;

            if (contentVal == null)
                return responseMessage;

            ConvertDateTimeDeep(contentVal);

            var processedResponse = request.CreateResponse(responseMessage.StatusCode, contentVal);
            responseMessage.Content = processedResponse.Content;
            return responseMessage;
        }

In the above method, in the line var responseMessage = await base.SendAsync(request, cancellationToken); already explodes the stauscode 500(Internal Server Error). Already the var(Object) contentVal is where I get the errors and when I call ConvertDateTimeDeep passing contentVal, already Zica everything. I just wanted to understand why he does not enter the Builder.

Convertdatetimedeep

private void ConvertDateTimeDeep(object contentVal)
        {
            var scannedObjects = new HashSet<object>(new[] { contentVal });
            var userTimeZone = HttpContext.Current.GetUserTimeZone();
            if (typeof(IDictionary<object, object>).IsAssignableFrom(contentVal.GetType()))
            {
                var collection = (contentVal as IDictionary<object, object>).Values;
                foreach (var item in collection)
                    ConvertDateTimeDeep(item, userTimeZone, scannedObjects);
            }
            else if (typeof(IDictionary<string, object>).IsAssignableFrom(contentVal.GetType()))
            {
                var collection = (contentVal as IDictionary<string, object>).Values;
                foreach (var item in collection)
                    ConvertDateTimeDeep(item, userTimeZone, scannedObjects);
            }
            else if (typeof(IEnumerable<object>).IsAssignableFrom(contentVal.GetType()))
            {
                var enumerable = contentVal as IEnumerable<object>;
                foreach (var item in enumerable)
                    ConvertDateTimeDeep(item, userTimeZone, scannedObjects);
            }
            else
                ConvertDateTimeDeep(contentVal, userTimeZone, scannedObjects);
        }

When I change the route on the controller to this

[Route("api/v1/[controller]")]
    [Description("doc0x03303001")]
    public class OrdersController : ApiController
    {
        private readonly OrdersManager _mng;
        private readonly IOrdersManager _mngs;

        //public OrdersController(){}

        public OrdersController(IOrdersManager mng)
        {
            if (mng == null)
                throw new ArgumentNullException(nameof(mng));

            _mngs = mng;
        }
}

caught the error below in Postman

{ "message": "An error has occurred.", "exceptionMessage": "Parameter Count Mismatch.", "exceptionType": "System.Reflection.Targetparametercountexception", "stackTrace": " at System.Reflection.Runtimemethodinfo.Invokeargumentscheck(Object obj, Bindingflags invokeAttr, Binder Binder, Object[] Parameters, Cultureinfo Culture) r n at System.Reflection.Runtimemethodinfo.Invoke(Object obj, Bindingflags invokeAttr, Binder Binder, Object[] Parameters, Cultureinfo Culture) r n at System.Reflection.Runtimepropertyinfo.Getvalue(Object obj, Bindingflags invokeAttr, Binder Binder, Object[] index, Cultureinfo Culture) r n at System.Reflection.Runtimepropertyinfo.Getvalue(Object obj, Object[] index) r n at System.Reflection.Propertyinfo.Getvalue(Object obj) r n at Solera.Solaris.Centralv2.Orders.Business.Http.Utcdatetimetolocaldatetimeconverterhandler.Convertdatetimerecursive(Propertyinfo prop, Object Owner, Timezoneinfo userTimeZone, Iset1 scannedObjs) in C:\\Projetos\\nova_central_v3\\nova_central_v3\\src\\CentralAPI\\Services\\Orders\\Business\\Http\\UtcDateTimeToLocalDateTimeConverterHandler.cs:line 113\r\n at Solera.Solaris.CentralV2.Orders.Business.Http.UtcDateTimeToLocalDateTimeConverterHandler.ConvertDateTimeDeep(Object contentVal, TimeZoneInfo userTimeZone, ISet1 scannedObjs) in C: nova_central_v3 nova_central_v3 src Centralapi Services Orders Business Http Utcdatetimetolocaldatetimeconverterhandler.Cs:line 77 r n at Solera.Solaris.Centralv2.Orders.Business.Http.Utcdatetimetolocaldatetimeconverterhandler.Convertdatetimedeep(Object contentVal) in C: nova_central_v3 nova_central_v3 src Centralapi Services Orders Business Http Utcdatetimetolocaldatetimeconverterhandler.Cs:line 57 r n at Solera.Solaris.Centralv2.Orders.Business.Http.Utcdatetimetolocaldatetimeconverterhandler.d__2.Movenext() in C: nova_central_v3 nova_central_v3 src Centralapi Services Orders Business Http Utcdatetimetolocaldatetimeconverterhandler.Cs:line 36 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 System.Web.Http.HttpServer.d__24.Movenext()" }

  • 1

    include an example of the post you’re doing

  • @Leandroangelo, this is the call on the Postman: http://localhost:24253/api/v1/orders/receiveassessment

  • You don’t have this route in your controller

  • Changing course, I caught this mistake: An error occurred when trying to create a controller of type 'Orderscontroller'. Make sure that the controller has a parameterless public constructor.

  • In the edition of the errors, I said that there were 4 errors, but in fact it is one, only the class sepaou, but the mistake is one. Read all at once and not error 1, error 2 and etc. I will edit and put as if it were a single error

1 answer

0

Try to change that stretch

[ApiVersion("1")]

For that:

[ApiVersion("v1")]
  • From 5 fell to 4 errors, but with this message after switching from 1 to v1: The specified API version is invalid.

  • You had commented that the code did not stop at the breakpoint of Action. I think you better post all the errors that the visual studio indicates.

  • 1

    I know, except now I see that there’s a class that concatenates the mistakes. I didn’t know it yet, hj is my second day and I already have this loofah, but everything I lift here, I will be posting to try to clarify and help more.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.