【问题标题】:Cannot deserialize the current JSON array into type model because the type requires a JSON object to deserialize correctly无法将当前 JSON 数组反序列化为类型模型,因为该类型需要 JSON 对象才能正确反序列化
【发布时间】:2021-10-29 21:43:29
【问题描述】:

我正在使用来自 asp.net Web 应用程序的 Web api,现在我遇到了这个问题。 我使用我的 web api 只是为了从我的数据库中检索数据并使用 jwt 来保证它的安全性。 另一方面,我有这个使用这个 web api 的 mvc web 应用程序。 当我运行我的 web-api 时,一切都很好,我可以轻松地检索我想要的数据,但在我的 web 应用程序中发生的情况并不相同。 有人可以帮我熟悉序列化以及为什么它没有从我的数据库中读取数据吗? 当断点到达“readTask.Wait();”行时弹出错误。

这是我的 WebApi 控制器:

public IHttpActionResult GetById (string id)
{
    ConnectionString();
    con.Open();
    SqlCommand com = new SqlCommand("oid_validation", con);
    com.CommandType = CommandType.StoredProcedure;
    com.Parameters.Add(new SqlParameter("@oid", id));
    SqlDataReader dr = com.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(dr);
    dt.TableName = "mytable";
    return Ok(dt);
}

这是我的模型类,它在我的 api 和我的网络应用程序上都是同一个。

public class v_websearch 
{
public system.guid ID {get; set;}
public system.DateTime DateSale {get; set;}
public system.DateTime From {get; set;}
public system.DateTime To {get; set;}
}

这是我用于消费 api 数据的网络应用控制器:

    public async Task<ActionResult> Confirm(string id)
    {
                var token = (string)Session["access_token"];
                V_WebSearch dt = null;
                using (var client2 = new HttpClient())
                {
                    client2.BaseAddress = new Uri("http://localhost:63443/api/");
                    client2.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                    var responseTask = client2.GetAsync("default/" + id);

                    var result = responseTask.Result;

                    #region Error Handlers
                    if (result.IsSuccessStatusCode)
                    {
                        var readTask = result.Content.ReadAsAsync<V_WebSearch>();
                        readTask.Wait();
                        dt = readTask.Result;
                        return View(dt);
                    }
               }
      }

【问题讨论】:

    标签: asp.net json .net asp.net-web-api consuming


    【解决方案1】:

    我喜欢 SOLID 原则! xD。

    • 您可以看到 GetById 的 Http 响应(查看 json 响应)它似乎不是您所期望的。

    • 对于HttpClient 试试GetFromJsonAsync 方法。

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    • 嗨@Hector,感谢您的回复。 1)。我添加了 HttpResponse,因为它是一个 API,我想看看它是否可以检索任何数据,您认为我应该将其更改为其他内容吗? 2)。我需要放置 HttpClient,因为在这种情况下,Web 应用程序是使用 API 的客户端。至少这是我对这项工作的想法,如果你认为我们可以用另一种方式让它工作,请告诉我。
    • 嗨!,我认为您的 Api 响应(来自 GetById 的 Http 响应)的格式不符合预期。你能分享这个 Json 响应吗?
    • 嗨,我对此代码的响应仅适用于我的 api,它仅在我运行 API 时向我显示数据,而不是在我的 mvc Web 应用程序中。但不知何故,我设法做到了,现在它工作正常。感谢您的宝贵时间,非常感谢。
    猜你喜欢
    • 2020-04-17
    • 2020-11-15
    • 2019-03-18
    • 2022-06-11
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多