Some time ago, I wrote a C# console app to call an API using
HttpClient
, and it works fine. It sends an XML request and deconstructs an XML reply. Now I need to call the same API from a webform browser app (.NET 4.7.2), so when the user clicks the button, the call is made, and when the answer is received, this is posted back to the page. Seems like a simple requirement, but using the working code from the console app fails here, perhaps thanks to asynchronous processing? What happens is the code gets to call the
ApiClient.PostAsync()
, then immediately returns out of the block, not running any subsequent code and, of course, not returning any value to the page.
What I have tried:
On the aspx page, I simply have a button handler like this:
protected void UltraSimpleButton_Click(object sender, EventArgs e)
{
MyApp.App_Code.API_Handler.InitializeClient(CertificateUserName, CertificatePassword);
var Reply = MakeRequest(XMLString);
}
The
InitializeClient
looks like this...
public static void InitializeClient(string CertificateUserName, string CertificatePassword)
{
System.Net.Http.HttpClientHandler MyHandler =
new System.Net.Http.HttpClientHandler();
ApiClient = new System.Net.Http.HttpClient(MyHandler);
ApiClient.BaseAddress = new Uri("https://test.someurl.com/services");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add
(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml"));
}
MakeRequest()
looks like this...
private async System.Threading.Tasks.Task<string> MakeRequest(string XMLString)
{
string ResponseString = "";
try
{
MyApp.App_Code.API_Communicator API_Class =
new MyApp.App_Code.API_Communicator();
ResponseString = await API_Class.SendRequest(XMLString);
}
catch (Exception ex)
{
return "Error " + ex.Message;
}
return ResponseString;
}
And the
API_Class.SendRequest
looks like this...
public async Task<string> SendRequest(string XMLString)
{
try
{
var CallContent = new StringContent(XMLString, Encoding.UTF8, "text/xml");
HttpResponseMessage ResponseReceived =
await API_Handler.ApiClient.PostAsync("", CallContent);
if (ResponseReceived.IsSuccessStatusCode)
{
}
else
{
}
}
catch (Exception ex)
{
throw new Exception("An error was detected while sending card details.
Error was '" + ex.Message + "'");
}
}
The
PostAsync
line is run, but control then immediately returns to the calling proc, and never to the next line. I know the call to the API is successful, but what I can't get it to do is wait until a reply is received, nor to continue to the next bit of code (so I can postback the reply). I have tried putting this in
MakeRequest()
...
var task = API_Class.SendRequest(XMLString);
task.Wait();
...but still, it does not wait! All the internet says is using APIs should be asynchronous, but that makes no sense in this situation, so how do I get it to wait for a reply?
Thanks in advance!