Can anyone explain CreatedAtRoute() to me?

martial picture martial · Jul 30, 2014 · Viewed 45.1k times · Source

From the template for Web API 2, a post method is always like this:

[ResponseType(typeof(MyDTO))]
public IHttpActionResult PostmyObject(MyDTO myObject)
{
    ...
    return CreatedAtRoute("DefaultApi", new { id = myObject.Id }, myObject);
}

I don't understand this CreatedAtRoute() method. Can anyone explain the CreatedAtRoute() method to me?

Answer

see sharper picture see sharper · Aug 4, 2014

The CreatedAtRoute method is intended to return a URI to the newly created resource when you invoke a POST method to store some new object. So if you POST an order item for instance, you might return a route like 'api/order/11' (11 being the id of the order obviously).

BTW I agree that the MSDN article is of no use in understanding this. The route you actually return will naturally depend on your routing setup.