使用 HttpClient PostAsync 发送的 C# NameValueCollection 问题

C# NameValueCollection problem send with HttpClient PostAsync

我遵循了这个答案

目标是通过 HttpCient

发送 https://my.address.com/api?mail_from=FromEmailAddress&mail_to=ToEmailAdress

找到这个解决方案:

private static readonly HttpClient client = new HttpClient { BaseAddress = new Uri("https://my.address.com") };

private async void Btn_send_Click(object sender, EventArgs e)
{
    NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
    
    queryString.Add("mail_from", FromEmailAddress);
    queryString.Add("mail_to", ToEmailAddress);
}

queryStringreturn我想要的=mail_from=FromEmailAddress&mail_to=ToEmailAddress

现在我想通过 HttpClient 发送它,但出现错误:

var response = client.PostAsync("/api?", queryString).Result;

错误:cannot convert from 'System.Collections.Specialized.NameValueCollection' to 'System.Net.Http.HttpContent'

我知道我很接近,请问有什么建议吗?

更新以完成这项工作:

var response = client.PostAsync($"/api?{queryString}", null);

您只需将查询字符串附加到 URI:

client.PostAsync($"/api?{queryString}", //...

第二个参数是HTTP内容,需要单独生成。

如果您没有任何内容要发送,您应该改用 HTTP GET:

client.GetAsync($"/api?{queryString}");

顺便说一句,您应该等待返回的 Task,而不是通过访问 Result:

进行阻塞
var response = await client.GetAsync($"/api?{queryString}");

你的解决方案差不多好了,你只需要保存扩展的uri。

//Init
var apiUri = "https://my.address.com/api";
var uriBuilder = new UriBuilder(apiUri);
var queryString = HttpUtility.ParseQueryString(uriBuilder.Query);

//Extend
queryString.Add("mail_from", FromEmailAddress);
queryString.Add("mail_to", ToEmailAddress);

//Overwrite original
uriBuilder.Query = queryString.ToString();
apiUri = uriBuilder.ToString();