Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Web API From Application

I have called Web API from ASP.NET page on a button click as below. This is perfectly working fine though I have read somewhere it will create deadlock as it is not async (due to use of .Result in line client.PostAsJsonAsync(url, sd).Result;)

Please suggest best way to update this code.

private void CallApi(SurveyData sd)
{

    using (var client = new HttpClient())
    {                

        string url = ConfigurationManager.AppSettings.Get("url");
        client.DefaultRequestHeaders.Accept.Clear();

        var response = client.PostAsJsonAsync(url, sd).Result;

        if (response.IsSuccessStatusCode) 
        { 
            Response.Write("Success");
        }
        else
        {
            Response.Write(response.StatusCode + " : Message - " + response.ReasonPhrase);
        }
    }
}
like image 415
Jigar Shah Avatar asked May 11 '16 05:05

Jigar Shah


1 Answers

If you don't want to use async then you could use WebClient instead of HttpClient.

WebClient client = new WebClient();
string response = client.UploadString(RequestUrl, "POST", data);
like image 105
Aamir Masood Avatar answered Nov 14 '22 23:11

Aamir Masood