c# - 在 Xamarin API 中向用户显示消息
问题描述
您有一个要使用的 API(不可修改),该 API 接收一些参数,如果它们没有得到正确验证,API 会抛出错误消息,这正是我想要捕获的消息,例如这里在图像中,我传递了一个错误的密码,并希望向用户显示该消息。
为此,创建一个名为 Response 的类,该类负责管理对 API 的不同调用
响应.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;
}
但我没有得到预期的回应(他给我画了空白信息!!!)
如果它带来消息,那就是对象!
对我有什么帮助吗?我究竟做错了什么?
解决方案
在您LoginViewModel
等待响应的方法中,您想要的变量userMessage
位于更深的一层。
目前:
// userMessage is null in your *locals* section
await dialogService.ShowMessage("Error", response.userMessage);
应该:
// This is where the wanted value is: userMessage is the desired message
await dialogService.ShowMessage("Error", response.Result.userMessage);
response.Result
由于您的 Result 变量是一个object ,因此您需要将您的转换为 Response ,但这应该可以解决您的问题。
应该是(铸造):
// This is where the wanted value is: userMessage is the desired message
await dialogService.ShowMessage("Error", (response.Result as Response)?.userMessage);
推荐阅读
- scala - 使用一个 when 子句添加多个列
- react-native - TypeError(RN 0.61.2):_firebaseApp.default.messaging 不是函数
- java - 将泛型抽象超类绑定到多个非泛型实现类
- dialogflow-es - DialgoFlow - 获取用户位置
- c# - 我的计算机上的无效登录尝试 - Asp .NET MVC 应用程序
- sql - Oracle Default null on converion error - 时间戳
- python - 运行函数时无法读取sqlite中的查询
- android - Kotlin:如何使用正则表达式映射 URL
- python - 如何使用 Python 将 FlatBuffer 消息从二进制转换为人类可读的文本格式?
- python-3.x - Pandas - 基于关键词提取