I have a problem, I made an api in .net 6 and I have a User model, with an incremental Id. I want that when I do a get from a user in swagger, it shows me all the data (including the ID), but if I make a Post I don't want the ID to appear in the body. How can I do it?
public class User
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
try
{
List<User>? user;
using (Context context = new())
{
user = context.Users.ToList();
}
return Ok(user.ToList());
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
[HttpPost]
public IActionResult Post(User value)
{
try
{
using (Context context = new())
{
context.Users.Add(value);
context.SaveChanges();
return Ok();
}
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
In the User class you must put the [SwaggerSchema(ReadOnly = true)] decorator, this will tell the swagger that it is read-only
Then you have to configure the Swagger, in the program.cs like this
Results:
GET
POST
I think this was what you were referring to, that your Id is autoincrementing and you didn't want it to appear in the body when making the post because it is supposed to change only as more records are entered.
Solve it using the Data Annotation
[JsonIgnore]
swagger
Response
SQLServer
It seems to me that what you are looking for is a different Request for your Post. I suggest you do the following:
Create a new class for the Post Request called NewUserDTO:
Then modify your post as follows:
Using DTOs in Requests helps you request only the required data.