Antonio Guerrero
Antonio Guerrero

Reputation: 73

Add Params HttpClient C#

I want to add a parameter, but I also have a body, I want to form this format:

HttpPost

http://localhost:8080/master/public/api/v1/invoice/send?token=123456

Currently I have:

HttpPost
http://localhost:8080/master/public/api/v1/invoice/send

 private readonly string UrlBase = "http://localhost:8080";
 private readonly string ServicePrefix = "master/public/api";



public async Task<DocumentResponse> SendInvoice<T>(Invoice body)
            {
            string controller = "/v1/invoice/send";
            try
            {

                var request = JsonConvert.SerializeObject(body);

                var content = new StringContent(
                    request, Encoding.UTF8,
                    "application/json");
                var client = new HttpClient();



                client.BaseAddress = new Uri(UrlBase);
                var url = string.Format("{0}{1}", ServicePrefix, controller);
                var response = await client.PostAsync(url, content);
                Debug.WriteLine(response);
                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return new DocumentResponse
                    {

                    };
                }
                var list = JsonConvert.DeserializeObject<DocumentResponse>(result);
                return list;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return new DocumentResponse
                {

                };
            }
        }

When I add it directly to the url, the request fails.

Advance

When I add it directly to the url, the request fails. Inquiring about HttpClient, I found this, but how do I add it having a body?

var parameters = new Dictionary<string, string> { { "token", "123456" } };
var encodedContent = new FormUrlEncodedContent (parameters);

Ref: C#: HttpClient with POST parameters

Thank you

Upvotes: 1

Views: 2663

Answers (1)

Simply Ged
Simply Ged

Reputation: 8672

When you format your URL you need to add the parameters like so:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token=123456", url);

Note the ? between the URL and the query parameter.

You don't specify how you get the value for token into your method but, if it is a readonly value similar to ServicePrefix you can pass it as a parameter to string.Format:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token={1}", url, Token);

You can always put this on one line, but I have split it to make it easier to read :-)

Upvotes: 1

Related Questions