我有一个使用此操作的ASP.Net Core Web API:
// POST api/TodoList
[HttpPost]
public void Post([FromBody] Tache tache)
{
TodoListContext.AjouterTache(tache);
}
这是Tache实体的代码:
public class Tache
{
public int Id { get; set; }
[DataType(DataType.MultilineText)]
[Required, MaxLength(250)]
public string Description { get; set; }
[DataType(DataType.Date)]
public DateTime DateCreation { get; set; }
[DataType(DataType.Date)]
public DateTime DateEcheance { get; set; }
public int Priorite { get; set; }
public bool Terminee { get; set; }
}
我使用XHR这样的javascript SPA调用动作:
function ajouterTache() {
// Construit un objet Tâche à partir des valeurs saisies
let tache = {};
tache.id = document.getElementById("idTache").value;
tache.dateCreation = document.getElementById("dateCreation").value;
tache.dateEcheance = document.getElementById("dateEcheance").value;
tache.priorite = document.getElementById("priorite").value;
tache.terminee = document.getElementById("terminee").checked;
tache.description = document.getElementById("description").value;
console.log(tache);
// Envoie la tâche à l'API
const req = new XMLHttpRequest();
req.onload = function () {
...
};
req.open('POST', uri, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(JSON.stringify(tache));
}
上面的代码可以正常工作,但是此代码不行:
function ajouterTache() {
data = new FormData(document.getElementById("formEdit"));
// Envoie la tâche à l'API
const req = new XMLHttpRequest();
req.onload = function () {
...
};
req.open('POST', uri, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(data);
}
表单的每个字段都具有正确的名称,已启用并且包含有效输入。
但是我总是得到“ 400:错误的请求”响应。
Firefox的调试工具在XHR结果中显示以下错误:
输入字符串'----------------------------- 18691991225667'是无效数字。路径”,第1行,位置43。title
:发生一个或多个验证错误
我在发送xhr来观看数据对象的内容之前添加了以下代码:
let formData = new FormData(document.getElementById("formEdit"));
for (let pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1] + ", " + typeof pair[1]);
}
结果如下:
idTache: 11
dateCreation: 2019-10-08
dateEcheance: 2019-10-22
priorite: 1
terminee: on
description: essai
这似乎是正确的。那么我使用FormData有什么问题呢?
如果您想使用来发布数据FormData
,则不应将其设置Content-Type
为。application/json
此外,请在action参数上使用[FromForm]
而不是[FromBody]
。
1.在js代码中删除以下行
req.setRequestHeader("Content-Type", "application/json");
2.使用[FromForm]
[HttpPost]
public void Post([FromForm] Tache tache)
结果如下:
idTache:11日期创建:2019-10-08日期编辑:2019-10-22优先级:1完成:描述:测试
由于您将数据作为Model Type接收Tache
,因此您需要传递一个名为属性,id
而不是idTache
在日志结果中显示。
您不显示视图代码,建议您将其name="id"
用于该输入文本框。
在我的情况下,正确的日志结果为__RequestVerificationToken:
,如果使用,也会被删除<form id="formEdit">
:
id: 11
dateCreation: 2019-10-08
dateEcheance: 2019-10-22
priorite: 1
terminee: on
description: essai
__RequestVerificationToken:xxxxxxxx
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句