-->

Can anyone explain CreatedAtRoute() to me?

2019-01-31 15:55发布

问题:

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?

回答1:

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.