好的,您可以在后端代码中添加错误处理逻辑,并在前端页面中显示错误信息。以下是具体步骤:
### 1. 修改后端控制器代码
在`Auth`方法中添加错误处理逻辑,并返回适当的错误信息:
```csharp
[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Auth([FromForm] LoginModel model)
{
if (model.Username == null || model.Password == null)
{
return BadRequest(new { message = "用户名和密码不能为空" });
}
string password = Md5String(model.Password);
var user = _generalContext.HrEmployees
.Count(employee => employee.IsActive && employee.IsLeave == 0 && employee.LocalId.ToUpper().Equals(model.Username.ToUpper()));
var user1 = _generalContext.SyssUsers
.Count(user => user.IsActive == 1 && model.Username.IsNullOrEmpty() && model.Password.IsNullOrEmpty() && user.LocalId.ToUpper().Equals(model.Username.ToUpper()));
if (user > 0 || user1 > 0)
{
var identity = new ClaimsIdentity("Cookies");
identity.AddClaim(new Claim(ClaimTypes.Name, model.Username));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return Redirect("/table");
}
else
{
return BadRequest(new { message = "用户名或密码错误" });
}
}
[HttpPost("out")]
public async Task<IActionResult> SignOut()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
private string Md5String(string input)
{
// Your Md5String logic here
return input; // Placeholder
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}
```
### 2. 修改前端页面代码
在前端页面中,使用 JavaScript 处理服务器返回的错误信息并显示给用户:
```html
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
<style>
.container {
max-width: 400px;
margin: 0 auto;
padding: 1em;
background-color: #f9f9f9;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.error {
color: red;
}
</style>
</head>
<body>
<div class="container">
<h1>登录</h1>
<form id="loginForm" action="api/auth" method="post">
<div>
<input type="text" id="username" name="Username" placeholder="用户名" />
</div>
<div>
<input type="password" id="password" name="Password" placeholder="密码" />
</div>
<button type="submit">登录</button>
</form>
<div id="errorMessage" class="error"></div>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async function (event) {
event.preventDefault();
const form = event.target;
const formData = new FormData(form);
const response = await fetch(form.action, {
method: form.method,
body: formData
});
if (response.ok) {
window.location.href = '/table';
} else {
const errorData = await response.json();
const errorMessageElement = document.getElementById('errorMessage');
errorMessageElement.innerText = errorData.message;
}
});
</script>
</body>
</html>