Home > Software engineering >  Can I ignore a property in an ASP.Net Core API model?
Can I ignore a property in an ASP.Net Core API model?

Time:05-19

I have a model on my API as follows:

namespace Models
{
    public class Car
    {
        public guid Id { get; set; }

        public string Name { get; set; }
    }
}

This model is used on a POST endpoint within my API which allows users to add cars to the system.

The problem I have is that Id is decided upon by the database. When posting this payload I want that the user does not specify the ID.

When I start my project and view the automatically generated swagger document the Id field is there and automatically populated.

How can I suppress this Id field so that the user will only send the car Name field in the JSON payload?

When the user will perform GET /car/12345, at that time I want the Id field returned in the JSON payload so I don't want to ignore it completely.

CodePudding user response:

If you're using Swashbuckle, you could install the Swashbuckle.AspNetCore.Annotations NuGet package, then use the SwaggerSchema attribute as follows:

namespace Models
{
    public class Car
    {
        [SwaggerSchema(ReadOnly = true)]
        public guid Id { get; set; }

        public string Name { get; set; }
    }
}

This will mark the property with the ReadOnly attribute in the generated OpenAPI document.

CodePudding user response:

If you want to completely exclude the property when accepting input, you can create a separate input model. The value of having an input model is that it reflects the specific subset of data required for that operation, not necessarily reflective of what is required by the database or for later retrieval, and allows you to separate behaviors like input validation so that you're not piling that responsibility onto your main DTO. There's now zero risk that a received input might somehow inject an ID or mishandle that property in a way you didn't intend.

public class CarInputModel 
{
   [Required]
   public string Name { get; set; }

   public Car ToCar() => new() { Id = Guid.Empty, Name = Name };
}

public class Car 
{
   public Guid Id { get; set; }

   public string Name { get; set; }
}

Once that input model has been received by your API, you can convert that input model into a Car, knowing you have full control over the inputs provided by the user.

  • Related