Using ActionResult class methods in API

Viewed 125

I was looking at a code example in this website and I noticed that in one endpoint it used Ok() return type and in the other one it just returned the object. When should I use ActionResult's methods such as Ok(), Created(), ... and when should we just return the object?

enter image description here

3 Answers

Comparing

return result;

return OK(result);

They will both work properly. When you use return result; you are actually making use of:

 public static implicit operator ActionResult<TValue>(TValue value);

and the Ok status (200) is the implied default.

So it is a matter of style but I would prefer the simpler return result; in combination with ActionResult<T> as it is type-safe. When you were to accidentally use return Ok(21); you would get a runtime error, not a compiler one.

You can use Ok(result) in the second case if you like. There is an implicit cast from T to ActionResult<T> that does the same as Ok(value), and this is the code that casts Employee in result to ActionResult<Employee>.

There is no such implicit cast to ActionResult which is used in the first case. It's not really possible to create an cast that makes sense.

If the first method returned Task<IEnumerable<Employee>>> then you could rely on the implicit cast and avoid using Ok().

Your second example relies on an implicit cast which turns your Employee into an ActionResult<Employee> which adds the Ok if you omit it. It's a short form of the first method. It makes your code slightly more readable at the expense of potentially confusing people that try to make sense of the seemingly differing return types.

Returning an OkObjectResult through the Ok method gives you

  • more fine-grained control over your answer as you could add more extension methods to configure your result and
  • allows you to return different status codes for different cases in your method, say 200 for one if branch and 404 for another.

Returning the actual object directly can make it easier for you to use tools such as Swashbuckle (OpenAPI) to automatically discover and create a technical description of your API. It is suitable for the simplest cases and implies Ok.

Related