Reputation: 26071
I'm trying to build an api using asp.net core 2. When posting from Postman the values received are 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": "[email protected]",
"FirstName": "bob",
"LastName": "barker",
"MobileNo": "00000000000"
}
Upvotes: 1
Views: 2014
Reputation: 46
As you're passing data in the body, [FromBody] could help here:
[HttpPost]
public Customer Post([FromBody] Customer customer)
You could bind model from various sources, more details could be found here https://tahirnaushad.com/2017/08/22/asp-net-core-2-0-mvc-model-binding/
Upvotes: 3