How do I catch Id on the return of a Web Api Post?

Asked

Viewed 1,437 times

2

I have this code on 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 the Controller of a project Asp.net MVC I get the answer so:

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

How to get Id in Sponse?

Thank you.

2 answers

0

If you only returned the whole, it would look like this:

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

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

dynamic retorno = response.Content.ReadAsAsync<ExpandoObject>().Result;
var id = content.id;

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);
}

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:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.