我有一个带有简单控制器的Web应用程序。Get方法可以正常工作,但我对post和put请求有问题。
[Route("api/[controller]")]
[EnableCors("AllowAll")]
public class LessonController : Controller {
...
[HttpPut("{id}")]
public void Put(int id, [FromBody] Lesson lesson) {
...
}
....
}Lesson在哪里
public class Lesson {
public int Id { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Description { get; set; }
public bool IsModerated { get; set; }
public int? PrevLessonId { get; set; }
public int? NextLessonId { get; set; }
}因此,我试图发送请求,但没有运气,而经验只是一个具有默认初始化属性的对象。我发送请求的方式有两种:第一种是使用js。
$.ajax({
type: "POST",
url: 'http://localhost:1822/api/lesson/1',
data: JSON.stringify({
lesson: {
description: "Fourth lesson description",
isModerated: true,
name: "Fourth lesson",
nextLessonId: 5,
prevLessonId: 3,
text: "Fourth lesson text"
}}),
contentType: "application/json",
success: function (data) {
alert(data);
}
});至于邮递员:

因此,内容类型是正确的。有人能告诉我与什么问题有关吗?
UPD:我尝试使用PostLesson模型,它包含来自Lesson但Id的所有属性,并通过Postman发送带有UpperCamelCase数据的请求,但这并没有解决我的问题。
发布于 2016-02-28 10:57:03
我已经解决了我自己的问题。事实上,这个问题很简单。我们只需要在Post方法中传递对象,该方法等于Lesson模型的结构,而不需要指定参数名。所以我的js代码看起来就像
$.ajax({
type: "POST",
url: 'http://localhost:1822/api/lesson/1',
data: JSON.stringify({
description: "Fourth lesson description",
isModerated: true,
name: "Fourth lesson",
nextLessonId: 5,
prevLessonId: 3,
text: "Fourth lesson text"
}),
contentType: "application/json",
success: function (data) {
alert(data);
}
});有关一些附加信息,请参见此链接。
https://stackoverflow.com/questions/35680547
复制相似问题