I'm trying to test this HttpRequest:
public void TestX(string baseUrl)
{
StringContent httpContentDistanza = new StringContent(GlobalVariables.JsonDistanza);
using HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(baseUrl)
};
HttpResponseMessage responseMessage = null;
try
{
responseMessage = httpClient.PostAsync("/xxx/xx/xxx", httpContentDistanza).Result;
// can't reach the code below
if (responseMessage.IsSuccessStatusCode)
{
string strContext = responseMessage.Content.ReadAsStringAsync().Result;
var risultato = JsonSerializer.Deserialize<Distanza1>(strContext);
GlobalVariables.DblAijCrnPsz = risultato.data.processDataIn.valore;
}
}
catch (Exception ex)
{
if (responseMessage == null)
{
responseMessage = new HttpResponseMessage();
}
responseMessage.StatusCode = HttpStatusCode.InternalServerError;
responseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
}
The problem is that the URI is not reachable, and I was expecting that its gonna throw some Exception, but it did not.
In case where URI is not reachable I need some how to catch that Exception.
I'm using BackgroundWorker
to run TestX()
:
public MainWindow()
{
InitializeComponent();
bgWorker = new BackgroundWorker { WorkerReportsProgress = true };
bgWorker.DoWork += ResetAll;
}
private void ResetAll(object sender, DoWorkEventArgs e)
{
var x = gestLink.TestX(GlobalVariables.BaseUrl).ToString();
//it also does't reach the code below
....
}
Update
I don't know what I'm doing wrong.. I still can't catch the exception :
public async Task TestX(string baseUrl)
{
StringContent httpContentDistanza = new StringContent(GlobalVariables.JsonDistanza);
using HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(baseUrl)
};
HttpResponseMessage responseMessage = null;
try
{
responseMessage = await client.PostAsync("/xxx/xxx/xx", httpContentDistanza);
if (responseMessage.IsSuccessStatusCode)
{
string strContext = await responseMessage.Content.ReadAsStringAsync();
var risultato = JsonSerializer.Deserialize<Distanza1>(strContext);
}
}
catch(Exception ex)
{
var error = ex.Message;
}
It crash here responseMessage = await httpClient.PostAsync("/xxx/xx/xxx", httpContentDistanza);
but stops in ResetAll()
and var x = this.
I have seen and read similar problems (Debugger stops after async HttpClient.GetAsync() and HttpClient.PostAsync and await crashing app) before, but no solutions have helped me. Any suggestions how to catch the exception?