0

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?

ewardz1
  • 29
  • 9
  • Maybe check the Result you get from POST? If its an unknown subsite you'll get 404 HttpCode. Maybe that helps – Leon Bohmann Dec 26 '20 at 12:48
  • How? After `ponseMessage = httpClient.PostAsync("/xxx/xx/xxx", httpContentDistanza).Result;` it crash and doesn't reach any line of code – ewardz1 Dec 26 '20 at 12:52
  • You have and asynchronous method called in an synchronous context. So basically PostAsync does not block and runs on another thread context. – Leon Bohmann Dec 26 '20 at 12:57
  • What you need to do is a) Put the Async call in an async method and decorate the call with an await or b) use a synchronous overload for HttpClient.Post – Leon Bohmann Dec 26 '20 at 12:58
  • @mjwills netcoreapp3.1 Btw, the call and the respons must be instant, that's why I don't want to use Async and Await. I should show the response in UI for 50 milliseconds max . – ewardz1 Dec 26 '20 at 13:09
  • 1
    `Btw, the call and the respons must be instant, that's why I don't want to use Async and Await.` What makes you think async / await makes it less instant? You may as well give async / await a try - it couldn't be any _slower_ than what you have now. ;) – mjwills Dec 26 '20 at 13:12
  • Does `.GetAwaiter().GetResult();` work rather than `.Result` (although, again, async await would be better). – mjwills Dec 26 '20 at 13:15
  • So it should be like this : `responseMessage = await httpClient.PostAsync("/iolink/sickv1/readDevice", httpContentDistanza);` ? – ewardz1 Dec 26 '20 at 13:36
  • Yes I try it : `public async void TestX(string baseUrl){...responseMessage = await httpClient.PostAsync("/iolink/sickv1/readDevice", httpContentDistanza);.....}` Its the same. It crash on `responseMessage = await httpClient.PostAsync("/iolink/sickv1/readDevice", httpContentDistanza)` – ewardz1 Dec 26 '20 at 13:55
  • Try putting .ConfigureAwait(false) after the call to the request, this could be a problem with sincronization context depending of .net version you are using – MestreDosMagros Dec 26 '20 at 19:35
  • @MestreDosMagros `responseMessage = await httpClient.PostAsync("/iolink/sickv1/readDevice", httpContentDistanza).ConfigureAwait(false);`nothing changed. I try that before – ewardz1 Dec 26 '20 at 20:16
  • https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void – mjwills Dec 26 '20 at 22:29

1 Answers1

1

You should change this:

public void TestX(string baseUrl) 

to

public async Task TestX(string baseUrl)

and this

responseMessage = httpClient.PostAsync("/xxx/xx/xxx",httpContentDistanza).Result;

to

responseMessage = await httpClient.PostAsync("/xxx/xx/xxx", httpContentDistanza);

Then you can handle Exceptions.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75