我不明白為什么當我嘗試登錄時,當我執行檢查以防止輸入的值為 null 時,程式回傳 System.NullReferenceException
這是模型:
using Newtonsoft.Json;
namespace StockingApp.Models
{
public class LoginModel
{
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
}
這是我用來登錄的代碼:
private async void loginButton_Clicked(object sender, EventArgs e)
{
LoginModel log = new LoginModel
{
Email = txtEmail.Text,
Password = txtPassword.Text
};
if (txtEmail.Text != null | txtPassword.Text != null)
{
Uri RequestUri = new Uri("The url of the Api");
var client = new HttpClient();
var json = JsonConvert.SerializeObject(log);
var contentJson = new StringContent(json, Encoding.UTF8, "application/json");
//this is the line that causes the exception
var response = await client.PostAsync(RequestUri, contentJson);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Iniciar Sesión", "El inicio de sesión se realizó correctamente", "Ok");
}
else
{
await DisplayAlert("Error", "Los datos introducidos son incorrectos", "Ok");
}
}
else
{
await DisplayAlert("Error", "Faltan datos por introducir", "Ok");
}
}
這是導致例外的行,我不明白為什么回應為空
var response = await client.PostAsync(RequestUri, contentJson);
這是 Xaml 和 Xaml 的外觀:它的外觀
<ContentPage.Content>
<StackLayout Spacing="5" Padding="10" VerticalOptions="Center">
<Entry x:Name="txtEmail" Placeholder="{translator:Translate prompt_email}" Style="{StaticResource entryStyles}"/>
<Entry x:Name="txtPassword" Placeholder="{translator:Translate prompt_password}" Style="{StaticResource entryStyles}" IsPassword="True"/>
<Button x:Name="loginButton" Text="{translator:Translate title_activity_login}" Style="{StaticResource buttonStyles}" Clicked="loginButton_Clicked"/>
<Label Text="{translator:Translate tit_contacto}" HorizontalTextAlignment="Center"/>
<Label x:Name="link" Margin="20" HorizontalOptions="Center">
<Label.FormattedText>
<FormattedString>
<Span Text="www.atecresa.com" TextColor="GreenYellow" TextDecorations="Underline">
<Span.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TapCommand}"
CommandParameter="https://atecresa.com" NumberOfTapsRequired="1"/>
</Span.GestureRecognizers>
</Span>
</FormattedString>
</Label.FormattedText>
</Label>
</StackLayout>
</ContentPage.Content>
這是大搖大擺的登錄:api的大搖大擺
我對 Postman 進行了檢查,并且 api 作業正常:Postman check
uj5u.com熱心網友回復:
我有一個類似的錯誤,我只是將url的http更改為https。我認為這就是這里的問題。
uj5u.com熱心網友回復:
也許試試這個
if (txtEmail.Text != null && txtPassword.Text != null)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/480352.html
標籤:api 休息 xamarin xamarin.forms 空引用异常
