Reputation: 6825
The following method compiles just fine and I would much rather this be a compile error:
[HttpGet("some/route")]
public ActionResult<string> GetSomething()
{
return Ok(23);
}
string
and int
are incompatible, but this compiles just fine. When using tools like Swagger (Open API), they generate endpoint definitions that are not correct.
I was wondering why ObjectResult
classes are not typed? Moreover, is there a workaround to this problem?
Edit:
I am trying to avoid bugs when swagger definition claims that a string
is returned, but instead, you actually get an int
. If int
s and string
s don't make sense, then imagine two random JSON objects DtoA
and DtoB
.
Upvotes: 1
Views: 535
Reputation: 28192
As far as I know, the response doesn't contains int and string type. The response body's type is text/plain, application/json or else.
So there is no need to check the int or string in OkObjectResult
's ActionResultObjectValue
value. Normally, there will all convert into string or byte as the
response content.
Besides, the swagger will generate the generate endpoint definitions according to the
ActionResult<Tvalue>
's Tvalue type.
If you return public ActionResult<int> GetSomething()
, you will find the result will convert into int
.
Update:
OkObjectResult inherits the ActionResult. The returned child class does not impact the Parent class compilation.This is by design.
ActionResult<T>
enables you to return a type deriving from ActionResult
or return a specific type.
To enforce compile error,you could just return int which is a specific type. And you could see the error message appear when you return int
.
Upvotes: 0