CreatedAtAction is a helper function that is typically used in POST and creation API requests. This method is not new by any means but it seems that the days of plain Ok() and Created() are over as more and more people shift.
But why do we need a fancy helper method for creating?
Why can’t we use a simple Ok() or Created()?
Why CreatedAtAction?
Using Ok() is nice, but when the response returns; that’s it. There is no other data being returned and all we are given back is a metaphorical thumbs up (which is not too descriptive but appropriate in some scenarios). We can pass in a string, number, or object, but once again for a huge API this likely isn’t sophisticated enough.
The three parameters of CreatedAtAction boil down to:
nameof(GetByCompanyName)
– This is the controller that will be executed after the function is run. CreatedAtAction is pretty much a fancy “controller runner” with the ability to return status codes at the same time.new { companyName = stockDto.CompanyName }
– this is the data that will be passed into the controller that you chose to execute above.stockModel
– this is the most amazing part ofCreatedAtAction
(in my opinion). You can put a DTO in the third parameter and it will shape it to your liking!
Conclusion
CreatedAtAction is a fantastic helper for returning the result of a POST. The whole idea is to create and immediately execute a GET, so that you can see what you just created.
Happy Coding!