Passing array of integers to WebAPI method in URI params?

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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

回答1:

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.



回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!