3

The client application accesses a web api controller to get a set of data , the controller has a list as parameter.

static void Main(string[] args)
{

    Program p = new Program();
    p.getdata().Wait();
}


public async Task getdata()
{
    List<string> datelist = new List<string>();
    datelist.Add("12/05/2017");
    datelist.Add("14/05/2017");
    datelist.Add("18/05/2017");

    HttpClient host = new HttpClient();
    host.BaseAddress = new Uri("http://localhost/widgetApi/");
    host.DefaultRequestHeaders.Clear();
    host.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    StringContent content = new StringContent(JsonConvert.SerializeObject(datelist), Encoding.UTF8, "application/json");



    HttpResponseMessage response = await host.GetAsync("api/dataAccessApi?"+ datelist);
    response.EnsureSuccessStatusCode();
   if( response.IsSuccessStatusCode)
    {

        Console.Read();
    }
}

The controller is

public HttpResponseMessage Get([FromBody] List<string> dates)
{
   ..... function going here
}

My question is how can I pass datelist to the web api ??

1
  • GET requests do not have a BODY, you can use query string values. ?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'... Commented Aug 2, 2017 at 12:31

1 Answer 1

6

GET requests do not have a BODY, you can use query string values. ?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'...

public HttpResponseMessage Get([FromUri] List<string> dates) {
   //..... function going here
}

On the client side you would need to construct the query string and append it to the Uri

var dates = datelist.Select(d => string.Format("dates={0}", UrlEncode(d));
var query = string.Join("&", dates);
var uri = "api/dataAccessApi?" + query;

With UrlEncode looking like this

/// <summary>Escape RFC3986 String</summary>
static string UrlEncode(string stringToEscape) {
    return stringToEscape != null ? Uri.EscapeDataString(stringToEscape)
        .Replace("!", "%21")
        .Replace("'", "%27")
        .Replace("(", "%28")
        .Replace(")", "%29")
        .Replace("*", "%2A") : string.Empty;
}

For Asp.Net Core consider to use [FromQuery] instead of [FromUri]

Sign up to request clarification or add additional context in comments.

1 Comment

Get([FromUri] List<string> dates) controllers parameter dates gives emptyArray,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.