WebApi controller action with comma-separated parameter values

Today I've run across an issue where I had to create a WebAPI GET action that could accept, among other things, a parameter with comma-separated values. If you ever need to implement this, then that's one way to do it:

Create an action filter###

The action filter will be used to intercept the action call and process the comma-separated parameter. Then, you simply assing the action filter to the controller action and you can carry on with the next task at hand.

A practical example###

First, let's create the action filter. Create a new class and name it something like ArrayInputAttribute. Then, copy and paste the following code:

using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ArrayInputAttribute : ActionFilterAttribute
{
	private readonly string parameterName;

	public ArrayInputAttribute(string paramName)
    {
    	this.parameterName = paramName;
        this.Separator = ',';
    }

	public char Separator { get; set; }

	public override void OnActionExecuting(HttpActionContext actionContext)
    {
		if (!actionContext.ActionArguments.ContainsKey(this.parameterName))
      	{
      		return;
      	}

		var parameters = string.Empty;
    	if (actionContext.ControllerContext.RouteData.Values.ContainsKey(this.parameterName))
    	{
    		parameters =(string)actionContext.ControllerContext.RouteData.Values[this.parameterName];
    	}
    	else if (actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[this.parameterName] != null)
    	{
    		parameters = actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[this.parameterName];
    	}

		if (parameters.Contains(this.Separator))
    	{
    		actionContext.ActionArguments[this.parameterName]            parameters.Split(this.Separator).Select(int.Parse).ToArray();
    	}
    	else
    	{
    		actionContext.ActionArguments[this.parameterName] = new[] { parameterers};
    	}
	}
}

Then, in your controller, create an action that accepts a comma-separated parameter like in the example below:

[HttpPost, HttpGet]
[ArrayInput("type", Separator = ',')]
public HttpResponseMessage SomeAction(int[] customerIds)
 {
 	try
 	{
 		// do something with the code
 	}
 	catch (Exception ex)
 	{
 		return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Some error!");
 	}
 }

This will allow you to call the WebAPI method like this:
http://yourWebAPIUrl/controllerName/SomeAction?type=1,2,3

The nice thing about this action filter is that you can define your own separator and parameter name, so it is quite versatile.

Happy coding...


  • Share this post on