如何在 Xamarin.Forms 应用程序的服务中组织 HTTP 响应

How to organize HTTP Responses in a Service in Xamarin.Forms app

我正在开发 Xamarin.Forms 应用程序。我的示例请求之一是:

        public async Task<CheckedUser> CheckUserAccount(User user)
        {
            try
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    clientMoeZdravje.DefaultRequestHeaders.Clear();
                    clientMoeZdravje.DefaultRequestHeaders.Add("Accept", "application/json");
                    var postData = JsonConvert.SerializeObject(user);
                    var response = await clientMoeZdravje.PostAsync($"api/User/CheckUser", new StringContent(postData, Encoding.UTF8, "application/json"));
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonMessage;
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                        {
                            jsonMessage = new StreamReader(responseStream).ReadToEnd();
                        }
                        CheckedUser responseData = (CheckedUser)JsonConvert.DeserializeObject(jsonMessage, typeof(CheckedUser));
                        return responseData;
                    }
                    else
                    {

                        return null;
                    }
                }
                else
                {

                    return null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                string error = ex.Message;
                return null;
            }
        }

如您所见,StatusCode 是否为 200 i return User 对象或 return null,但 null 表示没有互联网连接和错误请求。我不知道如何组织我收到的每一个回复。例如,如果 StatusCode 是 400/500/404 等到 return 字符串消息,或者如果没有互联网连接 return 消息用于 NoInternet,也用于异常 return 消息。组织此活动的最佳做法是什么?

您可以 return 使用 属性 responseStatusCode 而不是 return null 的 CheckedUser。

In your CheckedUser, add a new property let's say it responseStatusCode. Then you does not need to return null and you can return a new CheckedUser with responseStatusCode. After that you can check responseStatusCode every time you get response.