How can I code a Created-201 response using IHttpActionResult

Devsined picture Devsined · May 27, 2014 · Viewed 32.6k times · Source

How can I code a Created-201 response using IHttpActionResult ?

IHttpActionResult has only these options

  • Ok
  • List item
  • NotFound
  • Exception
  • Unauthorized
  • BadRequest
  • Conflict Redirect
  • InvalidModelState

What I am doing now is this code below, but I would like to use IHttpActionResult and not HttpResponseMessage

 public IHttpActionResult Post(TaskBase model)
        {
           HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, model);
          response.Headers.Add("Id", model.Id.ToString());
          return ResponseMessage(response);
         }

Answer

Gildor picture Gildor · May 27, 2014

If your view derives from ApiController, you should be able to call the Created method from base class to create such a response.

Sample:

[Route("")]
public async Task<IHttpActionResult> PostView(Guid taskId, [FromBody]View view)
{
    // ... Code here to save the view

    return Created(new Uri(Url.Link(ViewRouteName, new { taskId = taskId, id = view.Id })), view);
}