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

前端 未结 17 2010
孤独总比滥情好
孤独总比滥情好 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条回答
  •  Happy的楠姐
    2020-11-22 05:26

    I recently came across this requirement myself, and I decided to implement an ActionFilter to handle this.

    public class ArrayInputAttribute : ActionFilterAttribute
    {
        private readonly string _parameterName;
    
        public ArrayInputAttribute(string parameterName)
        {
            _parameterName = parameterName;
            Separator = ',';
        }
    
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionArguments.ContainsKey(_parameterName))
            {
                string parameters = string.Empty;
                if (actionContext.ControllerContext.RouteData.Values.ContainsKey(_parameterName))
                    parameters = (string) actionContext.ControllerContext.RouteData.Values[_parameterName];
                else if (actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName] != null)
                    parameters = actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName];
    
                actionContext.ActionArguments[_parameterName] = parameters.Split(Separator).Select(int.Parse).ToArray();
            }
        }
    
        public char Separator { get; set; }
    }
    

    I am applying it like so (note that I used 'id', not 'ids', as that is how it is specified in my route):

    [ArrayInput("id", Separator = ';')]
    public IEnumerable Get(int[] id)
    {
        return id.Select(i => GetData(i));
    }
    

    And the public url would be:

    /api/Data/1;2;3;4
    

    You may have to refactor this to meet your specific needs.

提交回复
热议问题