I've been looking for a few days for a way of doing a post request synchronously from an azure web app and haven't been able to make it work. Here is how it should work:
- I have an azure web service (an aspx) that receives post requests.
- Upon receiveing a request, the code behind of the aspx gets data from an external server. Thus it needs to make an http post request to external server and wait for the response.
- Once the code behind receives the external server response, it uses the data received to populate the aspx that will be in the response.
Steps 1 and 2 (just having an asp and populating the response) are just fine but I've struggled a lot with step 2. I have tried many versions of the code, which right now looks like this (simplified version without logs and some other variables and stuff):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace My_WebApp.EntryPoint
{
public partial class MyEntryPoint : System.Web.UI.Page
{
private string uriWebRequest = "https://some.web.server";
protected void Page_Load(object sender, EventArgs e)
{
// I only respond to post messages
if (Page.Request.HttpMethod == "POST")
{
// I need to send a post request to a server to
// get data to populate my web
var myTask = PostAsync(uriWebRequest, this.form1);
var result = myTask.Result;
}
}
static async Task<HttpResponseMessage> PostAsync(
string uriPeticion, HtmlForm form1)
{
try
{
using (var client = new HttpClient())
{
// I make the post request to the other server
// and wait for the response
HttpResponseMessage resp =
await client.PostAsync(uriPeticion, null)
.ConfigureAwait(false);
string respBody =
await resp.Content
.ReadAsStringAsync()
.ConfigureAwait(false); // This always returns empty
string respuestaRecibidaString = "";
if (string.IsNullOrEmpty(respBody))
{
respuestaRecibidaString = "Empty response";
}
else
{
respuestaRecibidaString = respBody;
}
// Show the http post response in my web app response.
form1.InnerText = respuestaRecibidaString;
return resp;
}
}
catch (HttpRequestException e)
{
System.Diagnostics.Trace.TraceInformation("(PostAsync) Error:");
System.Diagnostics.Trace.TraceInformation(e.Message);
return null;
}
}
}
}
This code always returns empty response from the external server request. Not even errors or anything (I've tried with postman and the external server does return something, either actual value or error). And I don't know wether that's from the client.postAsync function or what.
I've googled around and found a couple of things like this and this but haven't been able to make it work. Do you guys know what I'm doing wrong?
Thanks