chr*_*her 3 c# asp.net-web-api
客户端应用程序访问 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();
}
}
Run Code Online (Sandbox Code Playgroud)
控制器是
public HttpResponseMessage Get([FromBody] List<string> dates)
{
..... function going here
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何将 日期列表传递 给 Web api?
GET 请求没有 BODY,您可以使用查询字符串值。?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'...
public HttpResponseMessage Get([FromUri] List<string> dates) {
//..... function going here
}
Run Code Online (Sandbox Code Playgroud)
在客户端,您需要构造查询字符串并将其附加到 Uri
var dates = datelist.Select(d => string.Format("dates={0}", UrlEncode(d));
var query = string.Join("&", dates);
var uri = "api/dataAccessApi?" + query;
Run Code Online (Sandbox Code Playgroud)
看起来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;
}
Run Code Online (Sandbox Code Playgroud)
对于Asp.Net Core 考虑使用[FromQuery] 而不是 [FromUri]
| 归档时间: |
|
| 查看次数: |
21082 次 |
| 最近记录: |