Accepting multiple parameters the “RESTful” way using ASP .NET Web API

I came upon a require­ment at work to sup­port accept­ing mul­ti­ple ids in the Url of a “REST” request. I have no idea if this is actu­al­ly con­sid­ered RESTful or not, but the task was to for­mu­late the URL like so:

GET /FooResource/id1;id2;id3;id4/

The inten­tion was to be able to retrieve mul­ti­ple instances of FooResource with one request.

So, I came up with the fol­low­ing MVC ActionFilter to make my life a lit­tle bit easier:

ArrayInputAttribute

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

Usage

[HttpGet("FooResource/{ids}")]
[ArrayInput("ids", Separator = ';')]
public IEnumerable<FooResource> GetFoos(int[] ids)
{
    return ids.Select(id => _fooRepository.GetFoo(id));
}
Share