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 task was to formulate the URL like so:
GET /FooResource/id1;id2;id3;id4/
The intention 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:
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));
}