Home > Mobile >  jQuery ajax call get API that returns Task<ActionResult<List<ApiObject>>> keeps ge
jQuery ajax call get API that returns Task<ActionResult<List<ApiObject>>> keeps ge

Time:11-04

HTML:

<div id="api-calls" class="ui-drop-shadow">
    <button id="ajax" class="form-control">ajax call</button>
</div>

jQuery call is as below:

on(ajax, "click", function(event) { 
          alert('ajax');
           $.ajax({ 
               type: "GET",
               data: {SiteId: 8},
               dataType: "json",
               //dataType: "application/json, text/plain, */*",
               //dataType: "jsonp",
               //url: "https://localhost:44310/api/site/search?SiteId=8",
               url: "https://localhost:44310/api/site/search",
               success: function(data){        
                  alert(data);
               }
           });
        });

ASP.NET SiteController:

[HttpGet("[action]")]
public async Task<ActionResult<List<ApiObject>>> Search(int? SiteId)
{
 //Database logics that get to the 'recList' record list... all worked

 // finally, construct a list of the ApiObject for return, this is where the call failed
 // every time.
 recAPIList = recList.Select(a => new ApiObject()
            {
                ApiObjectId = a.ObjectId,
                Description = a.Description,
                Name = a.Name,
                IsDisabled = a.IsDisabled,
            })
            .ToList();

            return Ok(recAPIList);
}

as you can see, I've tried all kinds of combination of dataType in the ajax call, but all of then keeps failing at the final step in the ASP.NET controller that construct a list of return APIObjects.

The network response upon inspection gave the following error:

{"Type":null,"Title":"An unexpected error occurred!","Status":500,
"Detail":"The Instance value should be used to identify the problem when contacting support.\r\n
System.InvalidOperationException: Sequence contains more than one element\r\n   
at System.Linq.ThrowHelper.ThrowMoreThanOneElementException()\r\n   
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)\r\n   
at Controllers.SiteController.<>c__DisplayClass5_0.<Search>b__7(Site a) 
in \\Controllers\\SiteController.cs:line 167\r\n   
at System.Linq.Enumerable.SelectListIterator`2.ToList()\r\n   
at lambda_method(Closure , Object )\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)\r\n   
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n   
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n   
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n   
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)","Instance":"urn:nebraskadss:error:5eae0ea1-af8a-4cb9-9532-2060c922af93","Extensions":{}}

I also tried in the controller to replace that .ToList() Linq statement with a for loop to create the list of ApiObjects, still fail with the same error response.

I want to add that this endpoint is from an existing working application that has asp.net core back end and angular front end and it is meant to retrieve a list of objects. The only reason I am posting this question is because this exception only happens when I call it from jQuery!

Another thought is that all of the examples I found on jQuery API calls involves retrieving just a single object. So, can jQuery API call handle receiving multiple objects...

CodePudding user response:

If you read carefully:

Sequence contains more than one element

and

at System.Linq.Enumerable.Single

This means that you are doing .Single() on a Collection or Enumerable object, which is allowed, but then that Collection or Enumerable object produces 2 or more items.

Single() forces 1 result. If it finds 0 results, or 2 or more results, then it throws an error. You either need to fix the collection, or if that is not possible, consider using First() instead of Single().

Finally, it also looks like the error is caused by code that you are not showing. If recList is the result of a query, then you need to fix that query.

CodePudding user response:

you have to change the ajax request

            $.ajax({     
               url: "https://localhost:44310/api/site/search?siteId=8",
               type: "GET",
                dataType: "json",
                    success: function(data){        
                  alert( JSON.stringify(data));
               }

or keep the ajax but change the action header

[HttpGet("~/api/site/search/{siteId?}")]
public async Task<ActionResult<List<ApiObject>>> Search(int? siteId)
  • Related