I've got a scenario to invoke an API from a third party application. But since the request is by using HTTPClient, its async and thus I'm not able to return correct value to Ajax request.
Here is my code
[WebMethod]
public string getSampleData()
{
string url = "https://api.thirdparty.com/eport/?Key=200&resultsPerPage=1000";
using (HttpClient client = new HttpClient(new HttpClientHandler()))
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("sabcd@test.com:TEst12345");// ("sabcd@test.com:Pwd123");
string val = System.Convert.ToBase64String(plainTextBytes);
client.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
string k = responseBody;
return k;
}
return "";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
But it simply triggering error since await does not work there. So how can I deal with the situation wisely without any trouble.
Here is my AJAX call $('#btn_keyedin').click(function () {
$.ajax({
url: '../webservice1.asmx/getSampleData',
type: 'POST',
contentType: 'application/json',
datatype: 'JSON',
success: function (data) {
console.log(JSON.stringify(data));
},
error: function () {
}
});
});
Please help to solve this trouble
await
keyword can only be used in async
methods. As far as I know, WebMethod
cannot be async. You will have to change your await
s to .Result
or as other people said .GetAwaiter().GetResult()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.