[英]RestSharp fails on saving results
響應成功,我可以在 Visual Studio 中查看它,但是當我嘗試獲取返回的數據時,它的 null。
這是 API https://yoda-api.appspot.com/api/v1/yodish?text=I%20am%20yoda
這是我的代碼:
public class YodishModel { public string yodish { get; set; } } public class YodishResult { public YodishModel Result { get; set; } } public class YodishService : iService { public string GetText(string text) { Lazy<RestClient> client = new Lazy<RestClient>(() => new RestClient($"http://yoda-api.appspot.com/api/v1/yodish?text={text}")); var request = new RestRequest(); var response = client.Value.Execute<YodishResult>(request); if (response.IsSuccessful) { return response.Data.Result.yodish; } return null; } public string ToUrl(string text) { return HttpUtility.UrlEncode(text); } }
響應成功,我可以查看結果,但Result
是 null ( NullPointerException
)。
另外,有沒有辦法在這里使用參數而不是使用字符串插值? 'text' 是 URL 的一部分,官方不是參數。
在您的情況下,您使用不匹配的 object 進行反序列化。 這是我為解決它所做的:
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.