Last post Aug 16, 2020 03:24 PM by DA924
Aug 16, 2020 12:59 AM|Derstine|LINK
I'm trying to write my very first ASP.NET Core Web API Projects for a client.
I'm looking for advice if I'm creating my controllers the right way. Thank you.
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
public class TransactionController : ControllerBase
private readonly ITransactionService _transactionService;
public TransactionController(ITransactionService transactionService)
_transactionService = transactionService;
// GET: api/<TransactionController>
public async Task<IActionResult> GetAll()
return Ok(await _transactionService.GetAllAsync());
// GET api/<TransactionController>/5
public async Task<IActionResult> Get(int id)
return Ok(await _transactionService.GetId(id));
// POST api/<TransactionController>
public async Task<IActionResult> Create([FromBody] TRANSACTION transaction)
return Ok(await _transactionService.CreateAsync(transaction));
// PUT api/<TransactionController>/5
public async Task<IActionResult> Put(int id, TRANSACTION transaction)
return Ok(await _transactionService.UpdateAsync(transaction));
// DELETE api/<TransactionController>/5
public async Task<IActionResult> Delete(int id)
return Ok(await _transactionService.DeleteAsync(id));
Aug 16, 2020 06:38 AM|DA924|LINK
You seem to be on the right track with a thin controller, and it is using DI of a service object into the controller that is implementing seperation of concerns. I like to use the DTO pattern with the WebAPI client and WebAPI service keeping the DTO in a
classlib project called Entities. All projects in the solution that need to know about the DTO(s) have project reference to Entities.
Have you considered global exception handling in the WebAPI? It allows no try/catches in the controller or in any project code like your Transservice and all exceptions are caught and logged with Serilog doing the logging by the GEH.
Example code you can review.
Aug 16, 2020 09:38 AM|Derstine|LINK
Talking about DTO's, do I need a separate DTO for POST and PUT? I already know about DTO's and I've used them extensively in the past. I just don't use them in my example to hear another opinion about it. I usually don't exposed my model and use a DTO and
then map those DTO's to my model using Automapper.
Aug 16, 2020 03:24 PM|DA924|LINK
The DTO for POST, PUT or GET and any logic anywhere in the solution should be using the same DTO, which is achievable if all the DTO(s) are kept in a classlib project such as one named Entities, you can name it anything, and all projects have reference
to the Entities project as an example.