RestSharp 无法保存结果
RestSharp fails on saving results
响应成功,我可以在Visual Studio中查看它,但是当我尝试获取返回数据时,它是空的。
这是APIhttps://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
为空(NullPointerException
)。
另外,有没有办法在这里使用参数而不是使用字符串插值? 'text' 是 URL 的一部分,正式不是参数。
在您的例子中,您正在使用不匹配的对象进行反序列化。这就是我修复它的方法:
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。
响应成功,我可以在Visual Studio中查看它,但是当我尝试获取返回数据时,它是空的。
这是APIhttps://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
为空(NullPointerException
)。
另外,有没有办法在这里使用参数而不是使用字符串插值? 'text' 是 URL 的一部分,正式不是参数。
在您的例子中,您正在使用不匹配的对象进行反序列化。这就是我修复它的方法:
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。