Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ASP.NET Web Api, how can I make an 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

like image 547
rocketspacer Avatar asked May 03 '16 18:05

rocketspacer


People also ask

Can we have multiple get methods in Web API?

As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.

Can we send query parameters in delete request?

There's nothing wrong with using DELETE on a collection and filtering by query parameters.


1 Answers

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);
       ......
    }
like image 96
Mostafiz Avatar answered Oct 10 '22 03:10

Mostafiz