NET核心3 API模型绑定复杂类型与角度10



我有一个Angular 10应用程序,它调用。NET核心3 API。我有一个复杂的类型,我试图在POST上对其进行绑定建模,但遇到了问题。在Angular方面,我有一个带有数组的类型。NET端,我试图绑定到的类型包括List<gt;。我正在尝试使用List<gt;。POST上的数组值是正确的,但我在上的控制器中遇到了错误。NET端,特别是在尝试绑定时使用参数。下面是我收到的错误以及我的代码。

错误。。。。

"坏请求状态:400〃;

"JSON值无法转换为应用程序。模型。VideoCategoryModel[]";

角度类型。。。

export class Video {
constructor(public id?: number,
public title?: string,
public date?: string,
public description?: string,
public url?: string,
public enabled?: boolean,
public categories?: VideoCategory[]){ }
}
export class VideoCategory {
constructor(public id?: number,
public name?: string){ }
}

以下是发送到API 的JSON

{
"title":"Test Title",
"date":"2020-12-09",
"description":"Test Description",
"url":"C:\fakepath\Capture2.JPG",
"categories":{
"id":101,
"name":"Platform Tutorials"
}
}

NET核心控制器代码。。。。

模型。。。

public class VideoModel
{
public VideoModel()
{
Categories = new List<VideoCategoryModel>();
}
public int Id { get; set; }
public DateTime Date { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string VideoUrl { get; set; }
public bool Enabled { get; set; }
public List<VideoCategoryModel> Categories { get; set; }
}
public class VideoCategoryModel
{
public int Id { get; set; }
public string Name { get; set; }
}

控制器。。。

[HttpPost("addvideo")]
public IActionResult AddVideo([FromBody] VideoModel model)
{
try
{
//var id = _service.AddVideo(_mapper.Map<VideoModel, TaVideo>(model));
//return Ok(id);
return Ok();
}
catch(Exception ex)
{
return BadRequest($"Failed to add the new video: {ex}");
}
}

如有任何建议,我们将不胜感激。我显然遗漏了一些东西,或者需要重构我的绑定方式,但我不知道最好的方法。提前谢谢!

"JSON值无法转换为应用程序。模型。VideoCategoryModel[]";

基于您的VideoModel类,我们可以发现Categories属性应该是VideoCategoryModel对象的集合。正如@MohsinMehmood在评论中提到的,您应该在Angular前端代码中为categories字段提供一个数组。

"categories":[{
"id":101,
"name":"Platform Tutorials"
}] 

此外,请注意,您在url字段中传递文件路径,但该属性在模型类中被命名为VideoUrl,为了使模型绑定正常工作,您可以尝试在使用以下代码片段进行序列化和反序列化时指定JSON中存在的属性名称。

[JsonPropertyName("Url")]
public string VideoUrl { get; set; }

最新更新