marko marinovic marko marinovic - 2 months ago 36x
C# Question

C# httpclient get response

I used httpClient to send data to the server. I can check the response successfully, but my response string is in a php file. I don't know how to access this string in php with something like:

if user exist echo true;
else echo false;

I tried with WebClient class. It worked but I was unable to check if it's response is successful.

Here is the code:

public Boolean authorization(String korisnik, String zaporka)
var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>>
new KeyValuePair<string, string>("korisnik", korisnik),
new KeyValuePair<string, string>("zaporka", zaporka)

var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync("", content).Result;
if (response.IsSuccessStatusCode)
MessageBox.Show("success respond");
return false;
return true;

I need to get result in a php file output.


You want to check the Content has value, then ReadAsStringAsync() for the content. It's JSON though, so you'll need to parse it.

Here, I use JsonConvert.Serialize<Dictionary<string,string>>() from Json .NET to deserialize the JSON to a Dictionary<string, string> object, which you can use to access the data. May I also suggest using async and await to make use of asynchronous functions properly:

public async bool Authorization(string korisnik, string zaporka){
    try {
        //will always throw an exception if not successful

        var response = await client.PostAsync("", content);

        if (httpResponse.Content != null) {
            var responseContent = await httpResponse.Content.ReadAsStringAsync();

            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);

    catch (Exception ex) {
        Console.WriteLine("Error occured: " + ex.Message);