C
C#6mo ago
prodijay

What return method is appropriate for controller actions for SPA frontend?

I have a basic CRUD app with a React SPA and a Postgres database. I want to know what I should return in the controller actions, specifically for Get, Post, Put and Delete actions. I've inspected some docs like this: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/details?view=aspnetcore-8.0 which use RedirectToAction. However this doesn't seem like it makes sense to use for a React SPA. I've been unable to find any relevant information on this topic of appropriate return methods for SPA. Any help would be appreciated. For instance would it make sense to use the CreatedAtAction for my Post controller action? Or could I simply just return createdNoteDTO? I want to send the created object back to the frontend.
c#
[HttpPost("{studyId}")]
public async Task<ActionResult<NoteDTO>> CreateNote(int studyId, [FromBody] CreateNoteInput input)
{
Note newNote = new Note
{...};

_context.Notes.Add(newNote);
await _context.SaveChangesAsync();

var createdNoteDTO = new NoteDTO
{...};

return CreatedAtAction(nameof(CreateNote), new { id = newNote.Id }, createdNoteDTO);
}
c#
[HttpPost("{studyId}")]
public async Task<ActionResult<NoteDTO>> CreateNote(int studyId, [FromBody] CreateNoteInput input)
{
Note newNote = new Note
{...};

_context.Notes.Add(newNote);
await _context.SaveChangesAsync();

var createdNoteDTO = new NoteDTO
{...};

return CreatedAtAction(nameof(CreateNote), new { id = newNote.Id }, createdNoteDTO);
}
Additionally, what should I do regarding the delete action? I don't want to return anything but it seems I have to return something.
2 Replies
Joschi
Joschi6mo ago
You should return the most appropriate http response. For a post request that created some resource that would be 201 Created. https://ochzhen.com/blog/created-createdataction-createdatroute-methods-explained-aspnet-core For delete endpoints you could just return a 200 OK or maybe 204 No Content
ochzhen.com
Created, CreatedAtAction, CreatedAtRoute Methods In ASP.NET Core Ex...
In this post we will discuss Created, CreatedAtAction and CreatedAtRoute methods available in ASP.NET Core controllers and, in particular, answer such questions as what it is and why it is needed, how do these methods work and how to use them, how to pass parameters and create link for an action in a different controller, examples how to use dif...
prodijay
prodijayOP6mo ago
Great I think this is what I needed, thank you!
Want results from more Discord servers?
Add your server