@page "/login"
@inject HttpClient Http
@inject NavigationManager Navigation
<EditForm Model="@loginModel" OnValidSubmit="HandleLogin">
<DataAnnotationsValidator />
<ValidationSummary />
<div class="container">
<h1>登录</h1>
<InputText type="text" id="username" @bind-Value="loginModel.Username" placeholder="用户名" />
<InputText type="password" id="password" @bind-Value="loginModel.Password" placeholder="密码" />
<button type="submit">登录</button>
</div>
</EditForm>
@if (!string.IsNullOrEmpty(errorMessage))
{
<div class="alert alert-danger">@errorMessage</div>
}
@code {
private LoginModel loginModel = new LoginModel();
private string errorMessage;
private async void HandleLogin()
{
errorMessage = null;
try
{
var response = await Http.PostAsJsonAsync("api/auth/login", loginModel);
if (response.IsSuccessStatusCode)
{
// 登录成功,跳转到主页
Navigation.NavigateTo("/");
}
else
{
// 登录失败,显示错误信息
var result = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
errorMessage = result["Message"];
}
}
catch (Exception ex)
{
errorMessage = "请求失败:" + ex.Message;
}
}
}
225

被折叠的 条评论
为什么被折叠?



