首页 技术 正文
技术 2022年11月15日
0 收藏 426 点赞 3,051 浏览 945 个字

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

情况说明

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

前端 ajax 调用报错

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

postman 调用正常

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

服务端相关代码

[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 的解惑。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898