簡體   English   中英

當asp.net核心api方法類型為IEnumerable時如何返回dapper動態查詢<dynamic>並且沒有 newtonsoft.json 參考</dynamic>

[英]How to return dapper dynamic query when asp.net core api method type is IEnumerable<dynamic> and without newtonsoft.json reference

我希望在 asp.net 核心 api 方法類型為 IEnumerable 且沒有 newtonsoft.json 參考時返回簡潔的動態查詢。

If asp.net core api method type is IEnumerable<dynamic> and using Dapper dynamic query system'll throw exception System.InvalidCastException: Unable to cast object of type '<GetEnumerator>d__9' to type 'System.Collections.IDictionaryEnumerator' .

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using ServerApp.Helper;
using Dapper;

namespace ServerApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ShDjController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<dynamic> Get()
        {
           using(var cn = DB.GetConnection()){
               return cn.Query(@"select * from table");
           }
        }
    }
}

我知道可以使用NewtonSoft.Json將數據序列化為 json 字符串來處理這個問題,但它需要更多參考,如下面的代碼:

        [HttpGet]
        public string Get()
        {
           using(var cn = DB.GetConnection()){
               return JsonConvert.SerializeObject(cn.Query(@"select * from table "));
           }
        }

或者

services.AddControllers().AddNewtonsoftJson();

完整的錯誤日志:

System.InvalidCastException: Unable to cast object of type '<GetEnumerator>d__9' to type 'System.Collections.IDictionaryEnumerator'.
   at System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Csproj

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

表演示腳本:

CREATE TABLE Table
    ([col1] int, [col2] int)
;
    
INSERT INTO Table
    ([col1], [col2])
VALUES
    (1, 2),
    (3, 4),
    (5, 6)
;

所以我最近使用了 Dapper ORM,這對我來說非常有用

public string Index()
{
     using (var cn = new SqlConnection("Data Source=(local);Initial Catalog=Db;Integrated Security=True"))
     {
         return JsonConvert.SerializeObject( cn.Query(@"SELECT * FROM Accounts.[User]"));
     }
}

我什至不需要使用 JsonConvert.SerializeObject

public IEnumerable<dynamic> Index()
{
     using (var cn = new SqlConnection("Data Source=(local);Initial Catalog=InstgramWeb;Integrated Security=True"))
     {
           return  cn.Query(@"SELECT * FROM Accounts.[User]");
     }
}

無論您遇到什么錯誤,都可能與其他事情有關。 也許是一個特定的列? (或者可能是版本問題?)

編輯:它適用於 .NET Core 3.1,不適用於 .NET Core 3.0。 更新版本可以解決問題,否則我們可以使用 Newtonsoft.Json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM