【发布时间】:2019-11-16 22:53:00
【问题描述】:
我有一个带有 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"
}
}
发生的事情是我到达了我的端点,但(媒体值)参数始终是空值/默认值。它实际上并没有使用来自邮递员的 POST 请求正文中的数据填充任何内容。知道为什么我的模型类没有被框架填充吗?
这是调试器中模型参数的样子:
【问题讨论】:
-
你发送 'Content-Type: application/json' 吗?
-
是的。我补充说,因为我收到 415 错误,甚至没有达到我的终点。
标签: c# asp.net-core asp.net-core-webapi