Reputation: 65
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);
}
}
}
Upvotes: 7
Views: 7219
Reputation: 28540
You could rewrite the method as an async
method (in which case I'd suggest providing a return type of string
):
private async Task<string> CallApi(SurveyData sd)
{
string result = String.Empty;
using (var client = new HttpClient())
{
string url = ConfigurationManager.AppSettings["url"];
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.PostAsJsonAsync(url, sd);
if (response.IsSuccessStatusCode)
{
result = "Success";
}
else
{
result = response.StatusCode + " : Message - " + response.ReasonPhrase;
}
}
return result;
}
Then you could also await
the results of this call:
Response.Write(await CallApi(sd));
Though the call would need to be made from within another async
method. Otherwise you'd have to do Response.Write(CallApi(sd).Result);
, and I don't know if you'd see a significant improvement in performance then.
Upvotes: 0
Reputation: 1396
You may try with this method
public async Task<HttpResponseMessage> GetHttpClientResult<T>(string baseUrl, string url, T requestParam, bool isExternalLink = false,
string acceptMediaVerb = "application/json", HttpMethod requestMethod = null)
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
if (!isExternalLink)
{
client.BaseAddress = new Uri(baseUrl);
}
if (!string.IsNullOrEmpty(acceptMediaVerb))
{
if (acceptMediaVerb == "application/json")
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (requestMethod == HttpMethod.Get || requestMethod == null)
{
response = client.GetAsync(url).Result;
}
else if (requestMethod == HttpMethod.Post)
{
response = await client.PostAsJsonAsync(url, requestParam);
}
}
}
var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
return response;
}
catch
{
return new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
}
}
This is started to write as a generic method to handle api methods with a base url configured in your application itself or any external web request
Upvotes: 0
Reputation: 321
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);
Upvotes: 1