我有一个带有POST端点的Web API项目。我正在尝试使用带有JSON正文的请求来达到此端点,并将其转换为该端点的函数的参数。但是,我函数中的参数始终为空。
发布函数端点:
[HttpPost]
[Route("PostMedia/")]
public void UpdateMedia([FromBody] Media value)
{
string[] file = Directory.GetFiles(this.config.Value.JSONFileDirectory, value.Id.ToString() + ".json");
if (file.Length == 1)
{
try
{
using (StreamReader reader = new StreamReader(file[0]))
{
string json = reader.ReadToEnd();
}
}
catch (Exception e)
{
throw new Exception("Could not parse file JSON for ID: " + value.Id.ToString(), e);
}
}
}
我的媒体模型类及其CatalogBase父类:
public class Media : CatalogueBase
{
MediaType type;
MediaRating rating;
string genre;
public MediaType Type { get => type; set => type = value; }
public MediaRating Rating { get => rating; set => rating = value; }
public string Genre { get => genre; set => genre = value; }
}
public abstract class CatalogueBase
{
string name;
string description;
int id;
public string Name { get => name; set => name = value; }
public string Description { get => description; set => description = value; }
public int Id { get => id; set => id = value; }
}
JSON请求,我使用以下命令访问我的API:
{
"Media" : {
"Id": 1,
"Name": "Gettysburg",
"Description": "A movie set during the American Civil War",
"Type": "Movie",
"Rating": "Excellent",
"Genre" : "Drama"
}
}
正在发生的事情是我命中了端点,但是(Media value)参数始终为null /默认值。它实际上并没有用我从邮递员打来的POST请求正文中的数据填充任何内容。知道为什么我的模型类没有由框架填充吗?
这是调试器中模型参数的样子:
答案 0 :(得分:3)
模型绑定程序无法将传入的JSON映射到类定义。
从JSON中删除根对象以匹配对象模型
{
"Id": 1,
"Name": "Gettysburg",
"Description": "A movie set during the American Civil War",
"Type": "Movie",
"Rating": "Excellent",
"Genre" : "Drama"
}
或更新所需的模型以匹配发送的JSON。
public class MediaUpdateModel {
public Media Media { get; set; }
}
并将其用于操作
public void UpdateMedia([FromBody] MediaUpdateModel value) {
var media = value.Media;
//...
}