Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

When you use CreatedAtRoute, the first argument is the method name of the Get to the resource. The trick that is not so obvious is that, even with the correct method name specified, you must use the Name param on the HttpGet attribute for it to work.

So if the return in your Post is this:

return CreatedAtRoute("Get", new { newModel.Id}, newModel);

Then your Get method attribute should look like this even if your method is named Get:

[HttpGet("{id}", Name = "Get")]

This will not only return the new object (normally as JSON), it will set the Location header on the response to the URI that would get that resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top