C
C#2y ago
SWEETPONY

❔ What should web api controller return?

I can return Ok with some json as parameter. Or I can return simple string For example, I have method in controller:
[HttpGet("movies")]
public string GetMovies()
=> "12 angry men";
[HttpGet("movies")]
public string GetMovies()
=> "12 angry men";
Is it correct to return just a string?
9 Replies
Anton
Anton2y ago
it will work the preferred return is ActionResult<string>
SWEETPONY
SWEETPONYOP2y ago
ok, thanks!
Pobiega
Pobiega2y ago
a HTTP GET for an endpoint called "movies", I'd expect it to return an array/list of something
Amos
Amos2y ago
[HttpGet("movies")]
public async Task<ActionResult<List<Movie>>> GetMovies()
{
// maybe lookup in database or something
var movies = new List<Movie>
{
new Movie
{
Name = "12 Angry Men"
}
};

return Ok(movies);
}
[HttpGet("movies")]
public async Task<ActionResult<List<Movie>>> GetMovies()
{
// maybe lookup in database or something
var movies = new List<Movie>
{
new Movie
{
Name = "12 Angry Men"
}
};

return Ok(movies);
}
SWEETPONY
SWEETPONYOP2y ago
is is worth to serialize "movies" to json and than return Ok with it?
// var json = movies.ToJson();
// return Ok(json);
// var json = movies.ToJson();
// return Ok(json);
Amos
Amos2y ago
It'll serialise it automatically On the reading end you'd do like var movies = await httpClient.GetFromJsonAsync<List<Movie>>(URI);
SWEETPONY
SWEETPONYOP2y ago
ah ok, thanks
Anton
Anton2y ago
serialization is usually delegated to the framework, involved validation is usually not the serialization format can be controlled with attributes or filters in general
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server