Do you return a Resource URL?

Last updated by Brady Stroud [SSW] 8 months ago.See history

When the Web API creates a resource, it should include the URI of the new resource in the Location header of the response.

public Product PostProduct(Product item)
 {
 item = repository.Add(item);
 return item;
 }

Figure: Bad example – The response does not contain a reference to the location of the new resource

public HttpResponseMessage PostProduct(Product item)

{

    item = repository.Add(item);

    var response = Request.CreateResponse(HttpStatusCode.Created, item);



    string uri = Url.Link("DefaultApi", new { id = item.Id });

    response.Headers.Location = new Uri(uri);

    return response;

}

Figure: Good example – The response message contains a link in the header to the created resource (plus the “Created” status code is returned)


Adam Stephensen
We open source.Loving SSW Rules? Star us on GitHub. Star
Stand by... we're migrating this site to TinaCMS