【问题标题】:Error parsing HTTP POST request body in my web api endpoint在我的 Web api 端点中解析 HTTP POST 请求正文时出错
【发布时间】: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


【解决方案1】:

模型绑定器无法将传入的 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;

    //...
}

参考Model Binding in ASP.NET Core

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2021-10-05
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多