Web api passing array of integers to action method

后端 未结 4 440
滥情空心
滥情空心 2021-01-16 08:28

I have this web api method:

[HttpGet]
[Route(\"WorkPlanList/{clientsId}/{date:datetime}\")]
public async Task

        
4条回答
  •  盖世英雄少女心
    2021-01-16 09:03

    You get 0 on clientsId because the framework is unable to bind the value 4,5 in your example to a List. In this case you use a custom model binder that will parse the value into the type you want and bind it to your action parameter:

    [RoutePrefix("blabla/api/workplan")]
    public class WorkPlanController : ApiController {
    
        [HttpGet]
        [Route("WorkPlanList/{clientsId}/{date:datetime}")]
        public IHttpActionResult WorkPlanList([ModelBinder(typeof(ClientsIdBinder))]List clientsId, [FromUri]DateTime date) {
    
            var result = new { clientsId, date };
    
            return (Ok(result));
        }
    }
    
    public class ClientsIdBinder : IModelBinder {
    
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext) {
            if (!typeof(IEnumerable).IsAssignableFrom(bindingContext.ModelType)) {
                return false;
            }
    
            var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (val == null) {
                return false;
            }
    
            var ids = val.RawValue as string;
            if (ids == null) {
                return false;
            }
    
            var tokens = ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length > 0) {
                var clientsId = tokens.Select(s => int.Parse(s));
                if (bindingContext.ModelType.IsArray) {
                    bindingContext.Model = clientsId.ToArray();
                } else {
                    bindingContext.Model = clientsId.ToList();
                 }
                return true;
            }
    
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, "Cannot convert client ids");
            return false;
        }
    }
    

    Reference: Parameter Binding in ASP.NET Web API

提交回复
热议问题