【问题标题】:How to use singleton class for get and Post the json values in xamarin forms?如何使用单例类获取和发布 xamarin 表单中的 json 值?
【发布时间】:2020-05-05 19:12:17
【问题描述】:

我使用基于单例的 xamarin 应用程序来获取服务器值。通过 StackOverflow 在本站 (Show List in Xamarin consuming REST API) 搜索示例。但我对此有一点怀疑。没有人回复我对这个问题的评论。

我的代码:

public async Task<Response> GetList<T>(string urlBase, string servicePrefix, string controller)
    {
        try
        {
            var client = new HttpClient();          
            client.BaseAddress = new Uri(urlBase);
            var url = string.Format("{0}{1}", servicePrefix, controller);
            var response = await client.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = result,
                };
            }

            var list = JsonConvert.DeserializeObject<List<T>>(result);

            return new Response
            {
                IsSuccess = true,
                Message = "Ok",
                Result = list,
            };
        }
        catch (Exception ex)
        {
            return new Response
            {
                IsSuccess = false,
                Message = ex.Message,
            };
        }
    }

我怀疑这段代码中的响应是什么。它是一个单独的类或 HTTP 响应消息。但是我更改了 HTTP 响应消息,它在上面声明的变量(成功,消息)中给出了错误。

【问题讨论】:

    标签: xamarin.forms


    【解决方案1】:

    Response 是一个自定义类,如下代码,它包含三个属性。

        public class Response
        {
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public object Result { get; set; }
        }
    

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多