2016-08-30 66 views
0

我一直在使用简单的API开发ASP.NET核心如何使用Postman使用Json发布premitive类型?

[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); 
     } 
    } 
    } 
} 

然后在邮差我做了以下

  • 设置URL
  • 添加页眉
    • “内容类型” 为“application/json”
  • 设定的主体

    { “身份证”:51437665009 }

当我点击发送,我看到的请求到达服务器,但ModelState.IsValid是false并有例外的ModelState

  • 异常{Newtonsoft.Json.JsonSerializationException:不能反序列化当前JSON对象(例如{“name”:“value”})类型为 'System.Int64',因为该类型需要JSON原始值(例如 string,number,boolean,null)才能正确反序列化。若要修复此错误,请将JSON更改为JSON原始值(例如,字符串, 数字,布尔值,空值)或更改反序列化类型,以使其为正常的.NET类型(例如,不是像integer这样的基本类型,不是一个 集合类型,如数组或列表),可以从JSON对象反序列化 。 JsonObjectAttribute也可以添加到类型 中,以强制它从JSON对象反序列化。路径的 'id',第2行, 位置17.在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader 读卡器,类型的objectType,JsonContract合同,JsonProperty构件, JsonContainerContract containerContract,JsonProperty containerMember, 对象existingValue)在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader 读卡器,类型的objectType,布尔 checkAdditionalContent)}的System.Exception {Newtonsoft.Json.JsonSerializationException}

我也曾尝试发送id作为

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

回答

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); 
    } 
}