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

So I came upon a requirement at work to support accepting multiple ids in the Url of a "REST" request.  I have no idea if this is actually considered RESTful or not, but the idea was to formulate the URL like so:

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

The idea was to be able to retrieve multiple instances of FooResource with one request.

So, I came up with the following MVC ActionFilter to make my life a little bit easier:

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

It is used like this:

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

No Comments

Add a Comment