【发布时间】:2021-01-21 04:37:03
【问题描述】:
我正在阅读 .NET REST API 教程,该教程通过 sql server 后端为 .NET 中的命令行命令执行 CRUD。我正在使用邮递员向我的端点发送请求,如果我向我的端点发送一个发布请求,它只带有一个包含 CommandCreateDTO 的所有请求的对象,它会出现此错误:System.ArgumentException: Commander.Models.Command needs to have a constructor with 0 args or only optional args. (Parameter 'type')。想法?
控制器
//POST api/commands
[HttpPost]
public ActionResult<CommandCreateDto> CreateCommand(CommandCreateDto commandCreateDto)
{
var commandModel = _mapper.Map<Command>(commandCreateDto);
_repository.CreateCommand(commandModel);
_repository.SaveChanges();
return Ok(commandModel);
}
CommandReadDto
namespace Commander.Dtos
{
public class CommandReadDto
{
public int Id { get; set; }
public string HowTo { get; set; }
public string Line { get; set; }
public CommandReadDto(int Id, string HowTo, string Line)
{
this.Id = Id;
this.HowTo = HowTo;
this.Line = Line;
}
}
}
CommandCreateDto
namespace Commander.Dtos
{
public class CommandCreateDto
{
public string HowTo { get; set; }
public string Line { get; set; }
public string Platform { get; set; }
public CommandCreateDto(string HowTo, string Line, string Platform)
{
this.HowTo = HowTo;
this.Line = Line;
this.Platform = Platform;
}
}
}
命令模型
using System.ComponentModel.DataAnnotations;
namespace Commander.Models
{
public class Command
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(250)]
public string HowTo { get; set; }
[Required]
public string Line { get; set; }
[Required]
public string Platform { get; set; }
public Command(int Id, string HowTo, string Line, string Platform)
{
this.Id = Id;
this.HowTo = HowTo;
this.Line = Line;
this.Platform = Platform;
}
}
}
CommandsProfile
using AutoMapper;
using Commander.Dtos;
using Commander.Models;
namespace Commander.Profiles
{
public class CommandsProfile : Profile
{
public CommandsProfile()
{
//Source - Target
CreateMap<Command, CommandReadDto>();
CreateMap<CommandCreateDto, Command>();
}
}
}
【问题讨论】:
-
@PrasadTelkikar 工作感谢您的帮助!我是 DTO 的新手,所以现在我只是想知道它是如何做到的,哈哈
标签: c# asp.net .net asp.net-mvc rest