Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4143

Is it possible to make a Patch endpoint in .NET that only receives some entity properties in JSON?

$
0
0

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
  • Email
  • 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 = "test@test.com", Name = "Name A", LastName = "Smith" },            new User { Id = 2, Email = "test2@test2.com", 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.


Viewing all articles
Browse latest Browse all 4143

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>