0

I am wondering how to get the id of inserted record returned in http response to POST method

Controller method:

public HttpResponseMessage POST([FromBody]Map newmap)
{
try
  {
   using (SHATDbEntities entities = new SHATDbEntities())
    {
     entities.Maps.Add(newmap);
     entities.SaveChanges();
     var message = Request.CreateResponse(HttpStatusCode.Created, newmap);
     message.Headers.Location = new Uri(Request.RequestUri + newmap.Id.ToString());
     return message;
     }
   }
    catch (Exception ex)
   {
     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
   }
   }

Response Handled:

HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:2351/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.PostAsJsonAsync(RequestURI, newmap).Result;
int mapid = int.Parse(responsestatusCode.Content.ReadAsStringAsync().Result)

Explanation:

I tried other solution which available on stack overflow but didn't get solution and above code but it through an exception i.e here

weje
  • 69
  • 1
  • 7

1 Answers1

0

If using Entity Framework and have an Identity column set as primary key on table:

Taken from this SO: How can I get Id of inserted entity in Entity framework?

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

So after your .SaveChanges() call, check that your newMap object has the Id value populated on it.

If not using Entity Framework there are two solutions here: How to get last inserted id?

One is to use an OUT parameter, the other is the SCOPE_IDENTITY. Both will require changes to the underlying sql generated for your SaveChanges() method.

Your response.Content should just be a JSON representation of your newMap object. Deserialize it back to a Map and you can access it as such.

JSON deserialization should be as simple as:

var deserializedMap = 
    JsonConvert.DeserializeObject<Map>(response.Content);

You may also try:

var deserializedMap = JsonConvert.DeserializeObject<Map>(await response.Content.ReadAsJSonAsync());

Since your doing an async http request.

user7396598
  • 1,269
  • 9
  • 6
  • id is returned in htttp response message i wonder how to get that id from response message – weje May 09 '18 at 21:18
  • @weje If you debug, what is in your "response" object after the request is processed? It should be a json representation of your newMap object along with a Header, StatusCode, RequestMessage, and a couple other attributes. Is this the case? – user7396598 May 09 '18 at 21:44
  • yes exactly this my case how can i get that id from response – weje May 21 '18 at 19:10
  • @weje the easiest way is to deserialize the JSON back into your object graph. Then you can access all the attributes for the object, and you have an object to work with for things other than just pulling the id. Parsing the JSON itself is tedious and loses all of the other benefits of just having your object available. – user7396598 May 21 '18 at 19:58
  • thank you very much for your help i got the solution @user7396598 – weje May 23 '18 at 13:12