ajax 调用 .net core WebAPI,报错 400 (Bad Request) Unexpected character encountered while parsing value

此文由博主前两天的提问及 dudu 的回答整理,地址:https://q.cnblogs.com/list/myquestion

情况说明

基于 .net core 写了一个 Web API,用 postman 测试时,能够 POST 返回数据,但是用 ajax 调用 API 时就会报错(400)。

前端 ajax 调用报错

postman 调用正常

服务端相关代码

[HttpPost]
    public async Task<ActionResult<List<Flow>>> PostFlow([FromBody] PostParams data)  // dynamic
    {
        return await _context.Set<Flow>().Where(s => data.Czid.Contains(s.Czid) && s.Rq >= data.Begin && s.Rq <= data.End).ToListAsync(); } public class PostParams { public DateTime Begin { get; set; } public DateTime End { get; set; } public int[] Czid { get; set; } }

前端ajax

$.ajax({
    type: "POST",
    url: "http://localhost/rfapi/api/flow",
    data: {"czid": ["1"], "begin": "2017-03-30 00:00:00", "end": "2017-03-31 00:00:00"}, contentType: "application/json", async: true, dataType: "json", success: function(data) { console.log(data.length); }, error: function(err) { console.log(err); } });

关于此 Web API 的搭建过程,可参考 .net core WebAPI 初探及连接MySQL

解决方法

要用 JSON.stringify 将 js 对象转换为 json 字符串

data: JSON.stringify({"czid": ["1"], "begin": "2017-03-30 00:00:00", "end": "2017-03-31 00:00:00"})

感谢 dudu 的解惑。

猜你喜欢

转载自www.cnblogs.com/xunzhiyou/p/10727279.html