jQuery ajax call get API that returns Task<ActionResult<List<ApiObject>>> 不断收到 500 错误响应

jQuery ajax call get API that returns Task<ActionResult<List<ApiObject>>> keeps getting 500 error response

HTML:

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

jQuery调用如下:

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 站点控制器:

[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);
}

如您所见,我在 ajax 调用中尝试了 dataType 的各种组合,但所有这些都在 ASP.NET 的最后一步失败构建 return APIObjects 列表的控制器。

检查后的网络响应给出了以下错误:

{"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":{}}

我还尝试在控制器中用 for 循环替换 .ToList() Linq 语句来创建 ApiObjects 列表,但仍然失败并出现相同的错误响应。

我想补充一点,该端点来自现有的工作应用程序,该应用程序具有 asp.net 核心后端和 angular 前端,旨在检索对象列表。我发布此问题的唯一原因是因为此异常仅在我从 jQuery!

调用它时发生

如果你仔细阅读:

Sequence contains more than one element

at System.Linq.Enumerable.Single

这意味着您在 Collection 或 Enumerable 对象上执行 .Single(),这是允许的,但随后该 Collection 或 Enumerable 对象会产生 2 项或更多项

Single() 强制 1 个结果。如果它找到 0 个结果,或者 2 个或更多结果,则会抛出错误。您要么需要修复集合,要么如果不可能,请考虑使用 First() 而不是 Single().

最后,错误似乎是由您未显示的代码引起的。如果 recList 是查询的结果,那么您需要修复该查询。

您必须更改 ajax 请求

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

或保留 ajax 但更改操作 header

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