Reputation:
Here is some new code I just created with the scaffolding:
[ResponseType(typeof(Exam))]
public async Task<IHttpActionResult> GetExam(int id)
{
...
return Ok(exam);
}
Previously I had code such as this:
public HttpResponseMessage GetExam(int id)
{
...
return Request.CreateResponse(HttpStatusCode.OK, exam);
}
Can someone comment on what's behind the changes. Why the suggestion is now to use return types of "Ok" and is this different from coding HttpResponseMessage? I didn't yet find any documentation on this and in particular I am wondering what the ResponseType is doing? Any advice would be much appreciated.
Upvotes: 2
Views: 870
Reputation: 37540
In Web API version 1, you could either return HTTP 200 by returning a value, or you would have to construct a HttpResponseMessage
to return anything else.
In Web API 2, IHttpActionResult
and the associated Ok()
, BadRequest()
, Created()
, etc ApiController
methods were added to simplify many situations where you simply want to respond with a different status code. Behind the scenes, Web API calls IHttpActionResult.ExecuteAsync()
to convert it into an HttpResponseMessage
.
For more details, see: Action Results in Web API 2
As for the ResponseType
attribute, it's mainly there to specify the return type in actions that return IHttpActionResult
and HttpResponseMessage
so that Web API can generate the help documentation. Previously, this had to be done via config.SetActualResponseType()
.
More details: ResponseTypeAttribute
Upvotes: 3