Pass an array of integers to ASP.NET Web API?

前端 未结 17 1758
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:40

I have an ASP.NET Web API (version 4) REST service where I need to pass an array of integers.

Here is my action method:



        
17条回答
  •  再見小時候
    2020-11-22 05:16

    I have created a custom model binder which converts any comma separated values (only primitive, decimal, float, string) to their corresponding arrays.

    public class CommaSeparatedToArrayBinder : IModelBinder
        {
            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
            {
                Type type = typeof(T);
                if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String) || type == typeof(float))
                {
                    ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                    if (val == null) return false;
    
                    string key = val.RawValue as string;
                    if (key == null) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type"); return false; }
    
                    string[] values = key.Split(',');
                    IEnumerable result = this.ConvertToDesiredList(values).ToArray();
                    bindingContext.Model = result;
                    return true;
                }
    
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Only primitive, decimal, string and float data types are allowed...");
                return false;
            }
    
            private IEnumerable ConvertToDesiredArray(string[] values)
            {
                foreach (string value in values)
                {
                    var val = (T)Convert.ChangeType(value, typeof(T));
                    yield return val;
                }
            }
        }
    

    And how to use in Controller:

     public IHttpActionResult Get([ModelBinder(BinderType = typeof(CommaSeparatedToArrayBinder))] int[] ids)
            {
                return Ok(ids);
            }
    

提交回复
热议问题