Http requests with id (put, delete) don't work in ASP.NET Core 8

43 Views Asked by At

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)

Postman request

1

There are 1 best solutions below

0
Md Farid Uddin Kiron On

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.

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/50 instead it becomes like https://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/50 or /api/update/50

enter image description here

enter image description here

Solution:

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/50 then you should refactor your controller action as following:

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{

    [HttpPut("update/{id}")]
    public IActionResult UpdateUser(int id, [FromBody] UserModel userModel)
    {

       
    }

}

Note: Above modification would restore your endpoint route as https://localhost:7299/api/users/update/50

Output:

enter image description here

enter image description here

Note: Please refer to this official document if you want to study more.