首页 文章

如何使用 Json 使用 Postman 发布 premitive 类型?

提问于
浏览
0

我有使用 ASP.NET 核心开发的简单 API

[Route("api/[controller]/[action]")]
public class WorkunitController : Controller
{
    private IRepository _repository = null;
    public WorkunitController(IRepository repositoty)
    {
        _repository = repositoty;
    }       

    [HttpPost]
    public async Task SetTransformed([FromBody]long id)
    {
        if (ModelState.IsValid)
        {
            await _repository.SetTransformed(id);
        }
    }
  }
}

然后在 POSTMAN 我做了以下

  • 设置网址

  • 添加标题

  • “Content-Type”为“application/json”

  • 设置身体

{“id”:51437665009}

当我点击发送时,我看到请求来到服务器但是 ModelState.IsValid 是false并且 ModelState 中存在异常

  • 异常{Newtonsoft.Json.JsonSerializationException:无法将当前 JSON 对象(e.g. {“name”:“value”})反序列化为类型“System.Int64”,因为该类型需要 JSON 原语值(e.g. 字符串,数字,布尔值,空值)才能正确反序列化。要修复此错误,请将 JSON 更改为 JSON 原始值(e.g. 字符串,数字,布尔值,null)或更改反序列化类型,使其为普通.NET 类型(e.g. 不是整数类型的原始类型,不是集合类似于数组或 List 的类型,可以从 JSON 对象反序列化.JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化.路径'id',第 2 行,位置 17.在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader,Type objectType,JsonContract contract,JsonProperty 成员,JsonContainerContract containerContract,JsonProperty containerMember,Object existingValue)在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader,Type objectType,Boolean checkAdditionalContent)} System.Exception {。 4}

我也试过发送id作为

{ \"id\":\"51437665009\"}

1 回答

  • 0

    如果使用 json 作为数据类型,则需要创建用于绑定的自定义类

    public class PostModel
    {
        public long Id { get; set; }
    }
    
    [HttpPost]
    public async Task SetTransformed([FromBody]PostModel model)
    {
        if (ModelState.IsValid)
        {
            await _repository.SetTransformed(id);
        }
    }
    

相关问题