Rory Primrose

Learn from my mistakes, you don't have time to make them yourself

View project on GitHub

Using RestSharp to pass a set of variables to an ASP.Net MVC Web API action

Looks like a lot of people hit this issue and come up with lots of “interesting” solutions to get this to work. The answer is surprisingly simple however.

Assume that the controller action is like the following:

public HttpResponseMessage MyAction(
    [ModelBinder]List<string> referenceNames, DateTime startDate, DateTime endDate)

How do you get RestSharp to send the set of strings to the action so that they are deserialized correctly? The answer is like this.

var client = new RestClient(Config.ServiceAddress);
var request = new RestRequest(ActionLocation, Method.GET);
request.RequestFormat = DataFormat.Json;
request.AddParameter("ReferenceNames", "NameA");
request.AddParameter("ReferenceNames", "NameB");
request.AddParameter("StartDate", DateTime.Now.AddYears(-2).ToString("D"));
request.AddParameter("EndDate", DateTime.Now.AddYears(2).ToString("D"));

There are two things that make this work:

  1. Attribute the action parameter with [ModelBinder] – see here for more info
  2. Make multiple calls to request.AddParameter for the same parameter name

Do this and you should be good to go.

Written on February 15, 2013