[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] SigninViewModel formData)
{
MemberCredential membercredential = await db.MemberCredential.FirstOrDefaultAsync(t => t.MemberAccount.Equals(formData.memberAccount));
if (membercredential == null)
{
var test = new { success = false, message = "無此帳號,請重新輸入。" };
Console.WriteLine(test);
return BadRequest(new { success = false, message = "無此帳號,請重新輸入。" });
}
bool isPwdMatch = BCrypt.Net.BCrypt.Verify(formData.memberPassword, membercredential.MemberPassword);
Console.WriteLine("驗證結果:" + isPwdMatch);
if (isPwdMatch == false)
{
return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" });
}
var LoginData = new
{
MemberId = member.MemberId,
MemberName = member.MemberName,
MemberPoint = member.MemberPoint
};
string json = JsonSerializer.Serialize(LoginData);
Console.WriteLine(json);
HttpContext.Session.SetString(CDictionary.SK_LOINGED_USER, json);
return Ok(new { success = true, message = "登入成功" });
}
Input incorrect password and trigger the following code:
return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" }); However, the AJAX call does not execute the action.
Failed to load resource: the server responded with a status of 400 ()
document.getElementById("Login").addEventListener("submit", function (event) {
event.preventDefault();
let MemberAccount = document.getElementById("MemberAccount").value;
let MemberPassword = document.getElementById("MemberPassword").value;
const formData=
{
memberAccount:MemberAccount,
memberPassword:MemberPassword
}
$.ajax({
type:"POST",
url: "/api/Members/Login",
data:JSON.stringify(formData),
contentType: "application/json"
}).done(data=>{
if (data.success) {
alert("Login Success!");
window.location.href = "https://localhost:1111/Home/Index";
} else {
alert("Login fail!");
}
}).fail((jqXHR, textStatus, errorThrown) => {
console.error("AJAX error:", textStatus, errorThrown);
});;
});
If the login is successful, the AJAX call will display alert("Login Success!") and redirect to /Home/Index, however when an action with return BadRequest() is triggered, the AJAX call does not respond. In the browser's console, it shows Failed to load resource: the server responded with a status of 400 (). Please assist in rectifying the above program code, thank you! View image description here
public class SigninViewModel
{
public string memberAccount { get; set; }
public string memberPassword { get; set; }
}