【发布时间】:2017-09-01 18:54:59
【问题描述】:
我正在尝试使用 asp.net core 2 构建一个 api。从 Postman 发布时,收到的值为 null。
控制器
// POST api/customers
[HttpPost]
public Customer Post(Customer customer)
{
var c = customer;
c.AddedDate = DateTime.UtcNow;
context.AddAsync(c);
context.SaveChangesAsync();
return c;
}
型号
namespace AspDotNetCore.Models
{
public class CRUDContext : DbContext
{
public CRUDContext(DbContextOptions<CRUDContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
new CustomerMap(modelBuilder.Entity<Customer>());
}
}
public class BaseEntity
{
public Int64 Id { get; set; }
public DateTime AddedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string IPAddress { get; set; }
}
public class Customer : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string MobileNo { get; set; }
}
public class CustomerMap
{
public CustomerMap(EntityTypeBuilder<Customer> entityBuilder)
{
entityBuilder.HasKey(t => t.Id);
entityBuilder.Property(t => t.FirstName).IsRequired();
entityBuilder.Property(t => t.LastName).IsRequired();
entityBuilder.Property(t => t.Email).IsRequired();
entityBuilder.Property(t => t.MobileNo).IsRequired();
}
}
}
邮递员请求
{
"Email": "bob@bob.com",
"FirstName": "bob",
"LastName": "barker",
"MobileNo": "00000000000"
}
【问题讨论】:
-
stackoverflow.com/questions/45862459/… 的可能重复项。如果您觉得答案有用,请点赞;)
-
我认为你的
Customer类需要一个默认的构造函数(即使它是空的)来支持序列化和反序列化。只需在类中添加public Customer() { }并重试。 -
试试
public Customer Post([FromBody] Customer customer) -
@ElementalPete,在 C# 中已经给出了默认构造函数,因为它是从基类
object提供的。 -
@QualityCatalyst - 我以为我之前遇到过这个问题,但如果你包含一个非默认构造函数并且你不包含一个默认构造函数,这可能只是一个问题......我'在这个问题上我会听从你的。 :)
标签: c# asp.net asp.net-core postman