gpt4 book ai didi

c# - 将字符串列表从客户端传递到 Web API

转载 作者:行者123 更新时间:2023-11-30 21:39:01 25 4
gpt4 key购买 nike

客户端应用程序访问一个 web api Controller 来获取一组数据,该 Controller 有一个列表作为参数。

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();
}
}

Controller 是

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

我的问题是如何将 datelist 传递给 web api ??

最佳答案

GET 请求没有 BODY,可以使用查询字符串值。 ?dates='{UrlEncoded 日期}'&dates='{UrlEncoded 日期}'...

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]

关于c# - 将字符串列表从客户端传递到 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com