How to get Id on the return of a Post in the Api Web?

2

I have this code in Web Api :

    [ResponseType(typeof(Menu))]
    public async Task<IHttpActionResult> PostMenu(Menu menu)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Menus.Add(menu);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = menu.Id }, menu);
    }

In Controller of a project Asp.net MVC I get the answer like this:

var response = await client.PostAsJsonAsync("api/menus", menu);

How to get the ID no response?

Thank you.

    
asked by anonymous 07.06.2014 / 00:29

2 answers

0

Change your code like this:

[ResponseType(typeof(Menu))]
public async Task<IHttpActionResult> PostMenu(Menu menu)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Menus.Add(menu);
    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = menu.Id }, menu.Id);
}

Since in the last parameter of CreateAtRoute , you pass the return value.

To recover:

var response = await client.PostAsJsonAsync("api/menus", menu).Result;    
Int32 Id = response.Content.ReadAsAsync<Int32>().Result;

Reference:

07.06.2014 / 03:05
0

If you just returned the integer, it would look like this:

var retorno = response.Content.ReadAsAsync<int>().Result;

But I think it can be a problem because you created an anonymous object to return. Then use a dynamic object to serialize the return:

dynamic retorno = response.Content.ReadAsAsync<ExpandoObject>().Result;
var id = content.id;
    
07.06.2014 / 00:31