我正在尝试使用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"
}
答案 0 :(得分:2)
当您在身体中传递数据时,[FromBody]可以在这里提供帮助:
[HttpPost]
public Customer Post([FromBody] Customer customer)
您可以从各种来源绑定模型,可以在此处找到更多详细信息https://tahirnaushad.com/2017/08/22/asp-net-core-2-0-mvc-model-binding/