客户端应用程序访问web api控制器以获取一组数据,控制器有一个列表作为参数。
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();
}
}
控制器是
public HttpResponseMessage Get([FromBody] List<string> dates)
{
..... function going here
}
我的问题是如何将 datelist 传递给web api ??
答案 0 :(得分:3)
GET请求没有BODY,您可以使用查询字符串值。 ?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'...
public HttpResponseMessage Get([FromUri] List<string> dates) {
//..... function going here
}
在客户端,您需要构造查询字符串并将其附加到Uri
var dates = datelist.Select(d => string.Format("dates={0}", UrlEncode(d));
var query = string.Join("&", dates);
var uri = "api/dataAccessApi?" + query;
UrlEncode
看起来像这样
/// <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;
}
对于Asp.Net Core consider to use [FromQuery]而不是[FromUri]