-2

I followed this answer https://stackoverflow.com/a/1877016/3681759

goal is Send https://my.address.com/api?mail_from=FromEmailAddress&mail_to=ToEmailAdress via HttpCient

found this solution:

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

queryString return what i want = mail_from=FromEmailAddress&mail_to=ToEmailAddress

now i want to send it via HttpClient and error:

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

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

I know it im close, any advice please?

UPDATE to get this work:

var response = client.PostAsync($"/api?{queryString}", null);
Novice
  • 363
  • 10
  • 32
  • 1
    You need to append the query string onto the URI string, which is the first parameter. The second parameter is the content you want to post in the body of the request, which needs to be of type `HttpContent`, which is why your code isn't compiling.. – Martin Costello Oct 13 '20 at 07:44

2 Answers2

2

You simply need to append the query string to the URI:

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

The second argument is the HTTP content, which will need to be generated separately.

If you don't have any content to send, you should instead be using HTTP GET:

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

As an aside, you should be awaiting the Task that is returned, not blocking by accessing Result:

var response = await client.GetAsync($"/api?{queryString}");
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
1

Your solution is almost good, you just need to save the extended 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();
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • and what to add to ````var response = client.PostAsync( , );```` ? this has same error ````var response = client.PostAsync(apiUri, uriBuilder.Query).Result;```` – Novice Oct 13 '20 at 08:18
  • @novice As it was mentioned by Martin Costello the second parameter of the `PostAsync` [Reference](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync) is an `HttpContent`, your actual payload. Please also bear in mind that in case of POST most of the frameworks ignore the querystring (because it is designed to be used with GET) – Peter Csala Oct 13 '20 at 08:22