【发布时间】:2019-02-16 09:23:39
【问题描述】:
你有一个你想要使用的 API(不可修改),这个 API 接收一些参数,如果它们没有被正确验证,API 会抛出一个错误消息,这正是我想要捕获的消息,例如,在图像中,我传递了一个错误的密码并希望向用户显示该消息。
为此,创建一个名为 Response 的类,该类负责管理对 API 的不同调用
Response.cs:
public class Response
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
public object Result { get; set; }
[JsonProperty(PropertyName = "userMessage")]
public string userMessage { get; set; }
}
在我的 LoginViewModel 中,我调用了此 API 使用的方法,该方法在名为 ApiService.cs 的类中实现:
ApiService.cs:
public async Task<Response> GetLogin(
string urlAPILogin, string KeyLogin, string Rut, string Password)
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(urlAPILogin);
string url = string.Format("login/index/?k=" + KeyLogin + "&rut=" + Rut + "&password=" + Password);
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<Response>(result);
if (!response.IsSuccessStatusCode)
{
return new Response
{
IsSuccess = false,
Message = response.StatusCode.ToString(),
Result = model,
};
}
return new Response
{
IsSuccess = true,
Message = "Ok",
Result = model,
};
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
};
}
}
现在我想在我的 ViewModel (LoginViewModel) 中绘制该消息!我尝试通过以下方式捕获它:
var response = await apiService.GetLogin(
urlAPILogin,
KeyLogin,
Rut,
Password);
if (string.IsNullOrEmpty(response.userMessage))
{
IsRunning = false;
IsEnabled = true;
await dialogService.ShowMessage(
"Error",
response.userMessage);
Password = null;
return;
}
但我没有得到预期的回应(他给我画了空白信息!!!)
如果它带来消息,那就是那个对象!
对我有什么帮助吗? 我做错了什么?
【问题讨论】:
标签: c# json api xamarin xamarin.forms