rocketspacer rocketspacer - 1 month ago 12
C# Question

Passing multiple Id parameter to Web Api GET or DELETE request

I have a Bussiness Entity that is recognized by 2 Keys, for example:

class UserItem {
[Key]
[Column(Order = 1)]
public string UserId {get;set;}
[Key]
[Column(Order = 2)]
public string ItemName {get; set;}
public int Count {get; set;}
}


Now using a ASP.NET Web Api, how can i make a HTTP GET or HTTP DELETE to accept multiple parameters? Currently the default generated template only accept 1 key:

class ItemController : ApiController {
.....

//api/item/[key]
[HttpGet]
[ResponseType(typeof(UserItem))]
public async Task<IHttpActionResult> GetUserItem(string id)
{
UserItem item = await db.useritems.FindAsync(id);
......
}

......
}


db is my datacontext, i'm using EntityFramework 6 with ASP.NET Web Api 2

Answer

Map your route like below will allow you to pass two parameter, you can add more that two parameter this way

    [HttpGet]
    [Route("api/item/{id1}/{id2}")]
    [ResponseType(typeof(UserItem))]
    public async Task<IHttpActionResult> GetUserItem(string id1, string id2)
    {
       UserItem item = await db.useritems.FindAsync(id1);
       ......
    }