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);
}
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With