I'm developing a Rest API and I'm faced with a situation that I don't understand now. Http requests with id (put, delete) do not work. I get a 404 error in Postman. Thanks for the help.
Controller and method routing:
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
[HttpPut("/update/{id}")]
public IActionResult UpdateUser(int id, [FromBody] UserModel userModel)
{
if (userModel != null)
{
var existingUser = _db.Users.FirstOrDefault(u => u.Id == id);
if (existingUser != null)
{
existingUser.FirstName = userModel.FirstName;
existingUser.LastName = userModel.LastName;
existingUser.Email = userModel.Email;
existingUser.Password = userModel.Password;
existingUser.Phone = userModel.Phone;
existingUser.Photo = userModel.Photo;
existingUser.Status = userModel.Status;
_db.Users.Update(existingUser);
_db.SaveChanges();
return Ok();
}
return NotFound();
}
return BadRequest();
}
Program.cs:
app.MapControllers();
app.Run();
I also tried another variant of routing but requests do not work too:
[HttpPut("/{id}")]
public IActionResult UpdateUser(int id, [FromBody] UserModel userModel)
Well according to your shared code snippet, while you would define your API action with
HttpPut("/update/{id}")]your route no more remain like/api/users/update/50instead it becomes likehttps://localhost:7299/update/50.Which defines a fixed path "/update/" with an ID placeholder
({id}). As a result you are getting 404 no matter its/api/users/update/50or/api/update/50Solution:
Now the main question how you would like to have your route endpoint? If you want your route like
https://localhost:7299/api/users/update/50then you should refactor your controller action as following:Note: Above modification would restore your endpoint route as
https://localhost:7299/api/users/update/50Output:
Note: Please refer to this official document if you want to study more.