Passing array of integers to WebAPI method in URI

2019-06-24 13:41发布

I have the following:

    [HttpDelete]
    public HttpResponseMessage DeleteFolder(int[] ids)
    {

and I'm trying to use this:

DELETE http://localhost:24144/api/folder/1483;
DELETE http://localhost:24144/api/folder/[1483]

but these are coming up as null within the delete method - how do I send the data without putting it in the body (since this is a DELETE request)?

My routing has this:

            routes.MapHttpRoute(
           name: "Folder",
           routeTemplate: "api/folder/{id}",
           defaults: new { controller = "Folder", id = RouteParameter.Optional }
            );

2条回答
Viruses.
2楼-- · 2019-06-24 14:29

Nevermind, I found this:

http://blog.codelab.co.nz/2012/10/16/passing-arrays-into-asp-net-web-api-as-parameters/

Couldn't find an answer on SO though so I'll leave it here.

Exerpt from the above linked page:

[HttpGet()]
public HttpResponseMessage FindByMembers([FromUri]Int32[] ids = null)
{
   //Do stuff
    return Request.CreateResponseMessage(HttpStatusCode.OK);
}

The Url will be http://mywebsite/api/mycontroller/findbymembers/?ids=1&ids=2&ids=3.

查看更多
太酷不给撩
3楼-- · 2019-06-24 14:40

if you are looking to have Uri like api/folder/[1,2,3], the same parameter binding example mentioned in the below post's answer can be used here too :

How to send an array via a URI using Attribute Routing in Web API?

Note: You would need to change the following line to look for 'id' route variable rather than 'ids' as your route template here is 'api/folder/{id}'.

string idsAsString = actionContext.Request.GetRouteData().Values["id"].ToString();
查看更多
登录 后发表回答