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; }
}
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.
Aucun commentaire:
Enregistrer un commentaire