I have the following end point on my asp.net web api that I use to post new users and receive user object from body.
// POST: api/Users
[HttpPost]
public async Task<IActionResult> PostUser([FromBody] User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
user.DateCreated = DateTime.Now;
//user.LastLogin = DateTime.Now;
var hashedPassword = BCrypt.Net.BCrypt.HashPassword(user.Password);
user.Password = hashedPassword;
_context.User.Add(user);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
if (UserExists(user.Id))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
Console.WriteLine(ex.Message);
}
}
return CreatedAtAction("GetUser", new { id = user.Id }, user);
}
One property of user is a Role object defined by the following class:
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? LastUpdate { get; set; }
}
public class User
{
public int Id { get; set; }
public Role role { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime? DateCreated { get; set; }
public DateTime? LastLogin { get; set; }
}
The question is: How to I create a new user using the post endpoint? How to I pass the Role into user object? Note that I am able to create new user passing null on the role property. Now I want to pass an existing role.
This is what I am passing via Postman and angular2 app, but not getting through. return 201 status but not saving...
{
"role": {
"id": 1,
"name": "Admin",
"description": "Admin",
"dateCreated": "2016-01-01T00:00:00",
"lastUpdate": null
},
"firstName": "gggg",
"lastName": "gggg",
"emailAddress": "gggg",
"userName": "ggg",
"password": "$2a$10$z5dKRLqrus7i0fIluMynluJ8EOI2ko5vNGjBrBbfRaP738zHmc866",
"dateCreated": "2016-08-16T21:24:18.144517+02:00",
"lastLogin": null
}