Is it possible to create a Patch endpoint in .NET that only receives some entity properties in JSON and not a JSON full of things like what happens when we use JsonPatchDocument? I have a User entity that has the following properties:
- Name
- LastName
I want to create an endpoint that allows the client to send only the property they want to update, like in this example:
{ "Name":"Smith" }
All that be in this JSON should be operation “replace”.
But I only found these examples of Patch request in JSON:
[ { "op": "replace", "path": "LName", "value": "Smith" } ]
This is my current controller and endpoints:
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
namespace ApiWithAllEndpointsMethods.UI.Controllers
{
[ApiController]
[Route("Product")]
public class UserController : ControllerBase
{
private static List<User> users = new List<User>
{
new User { Id = 1, Email = "[email protected]", Name = "Name A", LastName = "Smith" },
new User { Id = 2, Email = "[email protected]", Name = "Name B", LastName = "Smith" },
};
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<User> patchDoc)
{
if (patchDoc == null)
{
return BadRequest();
}
var produto = users.FirstOrDefault(p => p.Id == id);
if (produto == null)
{
return NotFound();
}
patchDoc.ApplyTo(produto);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok(produto);
}
[HttpGet]
public IActionResult Get()
{
return Ok(users);
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string LastName { get; set; }
}
}
Does anyone have a example to how to create an endpoint without need pass all of these properties?
My goal with this is just to make my requests cleaner and similar to other HTTP methods.
1