0

I am trying to consume a WebAPI from a console application, as part of an integration test. I use this method:

private static string Consume(string endpoint, string user, string password)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(endpoint);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    string body = "{\"User\":\"" + user + "\",\"Password\":\"" + password + "\"}";   
    var response = client.PostAsync("api/ticket", new StringContent(body, Encoding.UTF8, "application/json")).Result;
    response.EnsureSuccessStatusCode();
    if (response.IsSuccessStatusCode)
            ... //process

    return string.Empty;
}

I don't feel very satisfied with the way I am sending the parameters to the WebAPI method, I prefer to use a typed object like:

public class Credentials
{
    public string User { get; set; }
    public string Password { get; set; }
}

and put it in the body. Does anyone has a suggestion for this?

Juanito
  • 420
  • 1
  • 4
  • 18
DanielV
  • 2,076
  • 2
  • 40
  • 61

2 Answers2

3

Use Newtonsoft.Json library to serialize your credential object. Your Consume function would be like this

private static string Consume(string endpoint, string user, string password)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(endpoint);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    var credential = new Credentials { User = user, Password = password };
    var credentialString = Newtonsoft.Json.JsonConvert.SerializeObject(credential, Formatting.None);


    var response = client.PostAsync("api/ticket", credentialString).Result;
    response.EnsureSuccessStatusCode();
    if (response.IsSuccessStatusCode)
            ... //process

    return string.Empty;
}

credentialString is serialize string of Credentials class object.

Suyog
  • 171
  • 7
2

You can use send object like this.

var _content = new StringContent(JsonConvert.SerializeObject(yourobject), Encoding.UTF8, "application/json");
var result = _client.PostAsync(yourapi, _content).Result;
Yashasvi
  • 197
  • 1
  • 3
  • 6