【问题标题】:Why am I getting an empty array json response from web api?为什么我从 web api 得到一个空数组 json 响应?
【发布时间】:2021-08-25 10:48:29
【问题描述】:

我有一个简单的 web api 项目,我试图使用 HttpClient 调用它(试图从数据库表中获取产品)。 尽管我已将数据存储在我的数据库(sqlServer)中,但我得到了一个空数组 [] 的结果。

API:

型号: 公共偏类产品 { 公共 int ID { 获取;放; } 公共字符串名称 { 获取;放; } 公共字符串类别 { 获取;放; } 公共小数价格 { 得到;放; } }

控制器: 公共类 ProductsController : ApiController { 私有 TestAPIContext db = new TestAPIContext();

    // GET: api/Products
    [ResponseType(typeof(Products))]
    public IQueryable<Products> GetProducts()
    {
        return db.Products;
    }

    // GET: api/Products/5
    [ResponseType(typeof(Products))]
    public async Task<IHttpActionResult> GetProduct(int id)
    {
        Products product = await db.Products.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        return Ok(product);
    }

    // PUT: api/Products/5
    [ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutProduct(int id, Products product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != product.Id)
        {
            return BadRequest();
        }

        db.Entry(product).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Products
    [ResponseType(typeof(Products))]
    public async Task<IHttpActionResult> PostProduct(Products product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Products.Add(product);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
    }

    // DELETE: api/Products/5
    [ResponseType(typeof(Products))]
    public async Task<IHttpActionResult> DeleteProduct(int id)
    {
        Products product = await db.Products.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        db.Products.Remove(product);
        await db.SaveChangesAsync();

        return Ok(product);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool ProductExists(int id)
    {
        return db.Products.Count(e => e.Id == id) > 0;
    }
}

HttpClient:

HttpClient 客户端 = 新的 HttpClient(); client.BaseAddress = new Uri("http://localhost:8090/");

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("api/Products").Result;

        if (response.IsSuccessStatusCode)
        {
            var products = response.Content.ReadAsStringAsync().Result;
            grvProducts.DataSource = products;

        }
        else
        {
            MessageBox.Show("Error Code" + 
            response.StatusCode + " : Message - " + response.ReasonPhrase);
        }

我做错了吗?

【问题讨论】:

  • 你在浏览器中尝试过HTTP请求吗?
  • 我得到以下信息:此 XML 文件似乎没有任何与之关联的样式信息。文档树如下所示。 w3.org/2001/XMLSchema-instance" xmlns="schemas.datacontract.org/2004/07/TestAPI.Models">
  • 我也和 Postman 一起检查过。我得到 [] 的回复
  • 问题出在服务器端。什么是技术? ASP.NET 核心?
  • 我使用 .NetFrameWork 4.8 和 VS2013

标签: c# httpclient webapi


【解决方案1】:

创建动作

    [Route("~/api/getallproducts")]
    public IEnumerable<Products> GetAllProducts()
    {
        return  db.Products.ToArray();
    }

并修复请求

 HttpResponseMessage response = client.GetAsync("api/getallProducts").Result;

if (response.IsSuccessStatusCode)
{
var stringData = response.Content.ReadAsStringAsync().Result;
var products = JsonConvert.DeserializeObject<List<Product>>(stringData);
 grvProducts.DataSource = products;
 }

【讨论】:

  • 谢谢,但这不起作用。我试过了。
  • @AlexandrosAngelopoulos 我更新了我的代码,它现在应该可以工作了
  • 再次感谢 Serge,但它不起作用。使用我的客户端代码和使用 Postman 仍然得到一个空数组......我认为客户端工作正常......这似乎是一个服务器端问题。由于某种原因它不会返回数据
猜你喜欢
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2023-03-17
  • 2014-01-22
  • 2021-03-18
  • 2020-08-31
  • 1970-01-01
相关资源
最近更新 更多