【问题标题】:RestSharp fails on saving resultsRestSharp 保存结果失败
【发布时间】:2020-10-12 07:01:44
【问题描述】:

响应成功,我可以在 Visual Studio 中查看,但是当我尝试获取返回的数据时,它为空。

这是 API https://yoda-api.appspot.com/api/v1/yodish?text=I%20am%20yoda

这是我的代码:

公开课 YodishModel
    {
        公共字符串 yodish { 获取;放; }
    }

    公共课 YodishResult
    {
        公共 YodishModel 结果 { 获取;放; }
    }
公共类 YodishService : iService
    {
        公共字符串GetText(字符串文本)
        {
            Lazy client = new Lazy(() => new RestClient($"http://yoda-api.appspot.com/api/v1/yodish?text={text}"));

            var request = new RestRequest();

            var response = client.Value.Execute(request);

            if (response.IsSuccessful)
            {
                返回 response.Data.Result.yodish;
            }

            返回空值;
        }

        公共字符串 ToUrl(字符串文本)
        {
            返回 HttpUtility.UrlEncode(文本);
        }
    }

响应成功,我可以查看结果,但是Result 为空(NullPointerException)。

另外,有没有办法在这里使用参数而不是使用字符串插值? 'text' 是 URL 的一部分,正式不是参数。

【问题讨论】:

    标签: c# restsharp


    【解决方案1】:

    在您的情况下,您正在使用不匹配的对象进行反序列化。这就是我修复它的方法:

    public class YodishModel
        {
            public string yodish { get; set; }
        }
    
        public class YodishService
        {
            public string GetText(string text)
            {
                Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"https://yoda-api.appspot.com/api/v1/"));
    
                var request = new RestRequest($"yodish").AddQueryParameter("text", Uri.EscapeDataString(text), true);
                var response = client.Value.Execute<YodishModel>(request);
    
    
                if (response.IsSuccessful)
                {
                    return Uri.UnescapeDataString(response.Data.yodish);
                }
    
                return null;
            }
        }
    

    如您所述,我还添加了 AddQueryParameter。

    【讨论】:

    • 我不明白为什么这行得通而我的不行,它似乎是相同的,但多了一个类。还有两个问题 - 1. 为什么是 AddQueryParameter 而不是 AddParameter? 2.为什么$"yodish"RestRequest中?我可能需要在 RestSharp 中进行更多练习,但是,这就是我这样做的原因。
    • 好吧,我想我明白了。我设法用AddParemeter 做到了。感谢您的帮助,标记为已解决。
    猜你喜欢
    • 2017-06-10
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多