【问题标题】:Why does my web API not return JSON?为什么我的 Web API 不返回 JSON?
【发布时间】:2018-06-07 13:55:05
【问题描述】:

我制作了一个非常简单的 Web API 控制器来在更复杂的控制器中重现错误,这个控制器只有最少量的代码来重现错误。

控制器代码如下

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace NWCloudBorgEmployee.Controllers
{

    public class WmsInfo
    {
        public string StoreName { get; set; }
        public string ItemName { get; set; }
        public string ItemQty { get; set; }
    }

    public class WmsInformation
    {
        public List<WmsInfo> WmsInfos { get; set; }
    }

    [Produces("application/json")]
    [Route("api/WmsInfo")]
    public class WmsInfoController : Controller
    {
        // GET: api/WmsInfo
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "You need to send in a barcode as ID to get the correct return data" };
        }

        // GET: api/WmsInfo/5
        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            var test = new WmsInformation();
            test.WmsInfos = new List<WmsInfo>
            {
                new WmsInfo { StoreName = "SE001", ItemName = "Item1" , ItemQty = "10"},
                new WmsInfo { StoreName = "SE002", ItemName = "Item2" , ItemQty = "115"}
            };

            return test.ToString();
        }
    }
}

当我调用 API 时,我得到如下字符串而不是 JSON 数据

"NWCloudBorgEmployee.Controllers.WmsInformation"

为什么不返回 JSON?

【问题讨论】:

  • test.ToString() 是默认的吗?如果它是默认值,您不应该覆盖它吗?

标签: c# json asp.net-core-webapi


【解决方案1】:

因为你在一个对象上调用.ToString()

将您的方法签名更改为:

public IActionResult Get(int id)

然后简单地说:

return Ok(test);

注意:您可以将签名更改为返回WmsInformation,但使用操作结果也可以轻松返回错误代码。

【讨论】:

  • 这么简单,千万不要在不眠之夜后写代码
  • @Matt idk,作为一个夜猫子,我在深夜做一些我最好的编码。不过,收益会递减:-D
  • 让我换个说法,因为喝得酩酊大醉,彻夜难眠后再也不要编码 :)
【解决方案2】:

我建议使用 JsonResult 而不是字符串

public JsonResult Get(int id)
    {
        var test = new WmsInformation();
        test.WmsInfos = new List<WmsInfo>
        {
            new WmsInfo { StoreName = "SE001", ItemName = "Item1" , ItemQty = "10"},
            new WmsInfo { StoreName = "SE002", ItemName = "Item2" , ItemQty = "115"}
        };

        return new JsonResult(test);
    }

希望对你有用

【讨论】:

    【解决方案3】:

    这是有效的 JSON。它是一个字符串,就像你的返回类型一样。

    我想你正在尝试序列化对象,而不是使用 ToString,它会默认返回类型名称。

    您可以只返回对象而不是使用 ToString,并调整您的方法签名以适应更改。

    这将启动内容协商过程并最终将您的对象序列化为(可能)JSON。

    public WmsInformation Get(int is)
    {
        var test = new WmsInformation
        {
            WmsInfos = ...
        }
    
        return test;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多