Home > Mobile >  What should a client be sending when creating an entity in ASP.NET Core?
What should a client be sending when creating an entity in ASP.NET Core?

Time:01-03

I'm creating an API using ASP.NET Core which has no visual component to it. In my controller I have a POST method, to which the client passes an instance of a model class.

I override some fields of the incoming model and then send it to my database.

class MyModel
{
    public Guid ID { get; set; }
    public DateTime CreationTime { get; set; }
    public String Name { get; set; }
}

[Route("api/[controller]")]
public class IntermediaryController : ControllerBase
{
    protected async Task<ActionResult<MyModel?>> Create(MyModel entity)
    {
        entity.ID = new Guid(); // Storage sets this if it's empty
        entity.CreationTime = DateTime.Now;
        return _storage.Create(entity);
    }
}

I'm wondering since I don't want them submitting their own Guid or DateTime, maybe I should create a cut down model, which just contains the fields they can submit. I'm fairly new to ASP.NET Core Web API, and I'm not sure if that's good practice, or just being overly verbose?

I can imagine ending up with a few versions of every model to cover slight variations of what I want the user to see/submit.

If I did go down this route, would those support classes still be called models, or are they then something else?

CodePudding user response:

Yes, your guess is correct - you should never send Model to or from client. OK, "never say never" - except in the most trivial cases. You need to shape what's called ViewModel or DTO (data transfer object - same thing) that will allow you to do exactly what you describe.

However, in POST APIs your server-side code can add an object to Entity Framework without ID, and assuming that the database generates ID, it will return the object with ID back to the model

CodePudding user response:

Post requests are meant for creating a new record. Ideally, databases should be designed to have the "ID" field as an identity column or your API should have its own logic to create a unique identifier for the record in database.

So, the request object in case of post requests should not contain a property to pass the unique identifier.

  • Related