简体   繁体   English

HttpClient.PostAsync 崩溃应用。 如何捕捉异常?

[英]HttpClient.PostAsync crash app. How to catch the Exception?

I'm trying to test this HttpRequest:我正在尝试测试这个 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.问题是 URI 不可访问,我期待它会抛出一些异常,但它没有。

In case where URI is not reachable I need some how to catch that Exception.如果无法访问 URI,我需要一些如何捕获该异常的方法。

I'm using BackgroundWorker to run TestX() :我正在使用BackgroundWorker运行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);它在这里崩溃responseMessage = await httpClient.PostAsync("/xxx/xx/xxx", httpContentDistanza); but stops in ResetAll() and var x = this .但在ResetAll()和 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.我以前看过并阅读过类似的问题( 调试器在异步 HttpClient.GetAsync() 和 HttpClient.PostAsync 之后停止并等待崩溃的应用程序),但没有解决方案对我有帮助。 Any suggestions how to catch the exception?任何建议如何捕捉异常?

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.然后你可以处理异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM