Regarding mvc4 web api

asp.net-mvc, asp.net-mvc-4, asp.net-web-api

Solution

public HttpResponseMessage PostProduct(Product item)
{
    //creates and adds an item to repository(db)
    item = repository.Add(item);
    //creates a new httpresponse
    var response =  Request.CreateResponse(HttpStatusCode.Created, item);
    //creates new uri 
    string uri = Url.RouteUrl("DefaultApi", new { id = item.Id });
    //set header for new uri
    response.Headers.Location = new Uri(uri);
    return response;
}

This lines will create a new RouteUrl -> basically a link for your response header.

My advice would be that you should start with official documentation from here: http://www.asp.net/web-api , it worked for me. There are many things to be researched here: http://geekswithblogs.net/JoshReuben/archive/2012/10/28/aspnet-webapi-rest-guidance.aspx

There are too many examples to be posted in this answer, that may help you.

· Response code: By default, the Web API framework sets the response status code to 200 (OK). But according to the HTTP/1.1 protocol, when a POST request results in the creation of a resource, the server should reply with status 201 (Created). Non Get methods should return HttpResponseMessage

· Location: When the server creates a resource, it should include the URI of the new resource in the Location header of the response.

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

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

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

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

  return response;
}

Problem

HEllo this is some piece of mvc4 webapi code can anyone over here explain me each line of code..I googled but didnt find any thing interesting ``` public HttpResponseMessage PostProduct(Product item) { item = repository.Add(item); var response = Request.CreateResponse(HttpStatusCode.Created, item); string uri = Url.RouteUrl("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); return response; } ``` I only understand that I am sending product item..and in return this web api returns me response of newly added product but I didnt understand this 2 lines in particular ``` string uri = Url.RouteUrl("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); ```

Original source