简体   繁体   中英

Xamarin.Forms Service return List<T> plus Status Code

This is the code from the service i generated.Everything work fine. I get the list of photos, but i want to get the status_code and make logic in the ViewModel and show message to the user.

 public async Task<IList<Photo>> GetAllPosts()
        {
            try
            {
                if (CrossConnectivity.Current.IsConnected)
                {
                    instagramCloneClient.DefaultRequestHeaders.Clear();
                    instagramCloneClient.DefaultRequestHeaders.Add("Accept", "application/json");
                    var response = await instagramCloneClient.GetAsync($"/photos");
                    var status_code=(int)response.StatusCode;
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonMessage;
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                        {
                            jsonMessage = new StreamReader(responseStream).ReadToEnd();
                        }

                        IList<Photo> photos = JsonConvert.DeserializeObject<IList<Photo>>(jsonMessage);
                        return photos;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {

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

I return list of photos. I also want response.StatusCode to the ViewModel from which i call the function.I must return IList, how to include some int status_code ? What is the best practice?

You have multiple options. You can create a new model with your List and an integer/enum for the StatusCode. Another option is to return a List of ArrayList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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