skip to Main Content
[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 = "登入成功" });
            
            
        }

Enter the wrong password, and execute

return BadRequest(new { success = false, message = "帳號或密碼錯誤,請重新輸入。" });
this code, but ajax 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, ajax will alert("Login Success!"),and
switch page to /Home/Index,but
the action about return BadRequest() is executed, but ajax does not make any action. In the developer’s introduction, it appears that Failed to load resource: the server responded with a status of 400 (), please help me to modify the above program code, thank you!
enter image description here

public class SigninViewModel
{
    public string memberAccount { get; set; }
    public string memberPassword { get; set; }
}

2

Answers


  1. When you return BadRequest() in backend, It will return 400 state code in response, So you need to handle it in fail() method. refer to this code:

    .fail((jqXHR, textStatus, errorThrown) => {
                if (jqXHR.status === 400) {               
                    const errorResponse = jqXHR.responseJSON; 
                    alert(errorResponse.message); 
                } else {
                    console.error("AJAX error:", textStatus, errorThrown);
                }
            });
    

    enter image description here

    Login or Signup to reply.
  2. Have you tried to use [FromBody] in the controller parameter.

    The endpoint signature should be like this.

    [HttpPost("Login")] public async Task Login([FromBody]SigninViewModel scv)

    If this not work defintely has to be related to the way you are sending the data from the frontend.

    Please make us know if you try this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search