简体   繁体   中英

ASP.NET MVC Failed AJAX Post Request

I am developing a web page in ASP.NET MVC. The page allows you to create a new password. After the user fills in the data on the form and clicks on the "Change password" button, the password will be changed in the firebase. When I run the page normally (localhost) it works perfectly. But when I try to access by ip and click on the button it doesn't do anything. After inspecting, I realized that there was a POST error. But it doesn't say exactly where it fails. How can I know the exact line on which it fails? Or maybe someone can help me with my code. Thanks to anyone who to help My code:

Index.cshtml

 <html>
<head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

    <script>

        // functions used to decrease time
        // if time runs out a method is called that changes the user's state to true
        // and update the page so that a message appears saying that the link is no longer available
        function startCountdown(timeLeft) {

            var interval = setInterval(countdown, 1000);

            update();

            function countdown() {

                if (--timeLeft > 0) {
                    update();
                } else {
                    clearInterval(interval);
                    update();
                    completed();
                }
            }
            function update() {
                hours = Math.floor(timeLeft / 3600);
                minutes = Math.floor((timeLeft % 3600) / 60);
                seconds = timeLeft % 60;

                if (minutes <= 9 && seconds <= 9) {
                    document.getElementById('time-left').innerHTML = '0' + minutes + ':0' + seconds;
                }
                else if (seconds <= 9 && minutes > 9)
                    document.getElementById('time-left').innerHTML = '' + minutes + ':0' + seconds;

                else if (minutes <= 9 || seconds > 9)
                    document.getElementById('time-left').innerHTML = '0' + minutes + ':' + seconds;
            }
            function completed() {
                $.ajax({
                    type: 'POST',
                    url: 'Home/MyAction',
                    data: {},
                    success: function (response) {
                        window.location.href = response.redirectToUrl;
                    }
                });
            }
        }

        function Verification() {
            var password = document.getElementById("password").value;
            var password1 = document.getElementById("password1").value;

            console.log(password);
            console.log(password1);

           // if password fields are empty
            // show the pop up
            if (password == "" && password1 == "") {
                console.log("Entrou no if (campos vazios)");
                document.getElementById('msg_alerta').innerHTML = "Empty fields";
                $('#exampleModal').modal('show');
            }// if passwords do not match
            else if (password != password1) {
                console.log("Entrou no if (password nao coincidem)");
                document.getElementById('msg_alerta').innerHTML = "Passwords do not match";
                $('#exampleModal').modal('show');
            }
           
            // if you are not going to change the password in the database
            else {
                $.ajax({
                    type: 'POST',
                    url: 'Home/ChangePassword',
                    data: {password},
                    success: function (response) {
                        window.location.href = response.redirectToUrl;
                    }
                });
            }
        };

        // will check the number of characters in the fields
        // if you don't respect it an error message will appear
        function checkPass() {
            var password = document.getElementById("password").value;
            var password1 = document.getElementById("password1").value;
            var error_password = document.getElementById('error-password');
            var error_password1 = document.getElementById('error-password1');

            var goodColor = "#66cc66";
            var badColor = "#ff6666";

            if (password.length == 0)
            {
                error_password.innerHTML = "";
            }

            if (password1.length == 0) {
                error_password1.innerHTML = "";
            }

            if (password.length >= 6) {
                document.getElementById("password").style.backgroundColor = "goodColor";
                error_password.style.color = goodColor;
                error_password.innerHTML = "Password OK!";
            }

             if (password1.length >= 6) {
                document.getElementById("password1").style.backgroundColor = "goodColor";
                error_password1.style.color = goodColor;
                 error_password1.innerHTML = "Password OK!";
            }
             if (password.length < 6 && password.length>0) {
                        document.getElementById("password").style.backgroundColor = "badColor";
                        error_password.style.color = badColor;
                        error_password.innerHTML = " You have to enter at least 6 digit!"
                    }
            if (password1.length < 6 && password1.length > 0) {
                document.getElementById("password1").style.backgroundColor = "badColor";
                error_password1.style.color = badColor;
                error_password1.innerHTML = " You have to enter at least 6 digit!"
            }

        }
    </script>
</head>
<body onload="startCountdown(600);">

    <p style="text-align:right;margin-right:100px;font-size:20px">Redirect in <span id="time-left"></span></p>

    @Html.AntiForgeryToken();

    <div class="form-group" style="text-align:center">
        <h4>Please enter a new password</h4><br />
        <h5>Enter Password</h5>
        <input type="password" id="password" , placeholder="Enter Password" onkeyup="checkPass(); return false;" />
    </div>
    <div class="form-group" style="text-align:center" id="error-password"></div>
    <div class="form-group" style="text-align:center">
        <h5>Confirm Password</h5>
        <input type="password" id="password1" , placeholder="Confirm Password" onkeyup="checkPass(); return false;" />
    </div>
    <div class="form-group" style="text-align:center" id="error-password1"></div>
    <br />
    <div class="form-group" style="text-align:center">
        <input type="submit" id="btn_Update" value="Change Password" class="btn btn-default" onclick="Verification()" />
    </div>

    @*pop up*@
    <div class="modal fade" id="exampleModal" runat="server">
        <div class="modal-dialog">
            <div class="modal-content" style="width: 400px; margin: 0 auto;">
                <div class="modal-header" runat="server">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h3 id="lblMasterMessage" style="text-align:center"><strong>Alerta</strong></h3>
                    <h4 style="text-align:center" id="msg_alerta"></h4>
                    <br />
                    <button class="btn btn-primary" id="btn_Update" data-dismiss="modal" style="text-align:right;float:right">Close</button>
                </div>

            </div>
        </div>
    </div>

</body>
</html>

Controller

 public class HomeController : Controller
    {

        string projectId;
        FirestoreDb fireStoreDb;
        User user = new User();
        UserRecord userRecord = null;

        
       // path to fetch the json file with the data to access the firebase
        string filepath = "C:/Users/Laura Saraiva/Documents/PagWeb_RecuperarConta/alonetogether-8dd98-firebase-adminsdk-kqb4h-e93709ec7f.json";

        //connection firebase
        public void ligacaoBD()
        {
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", filepath);
            projectId = "alonetogether-8dd98";
            fireStoreDb = FirestoreDb.Create(projectId);

        }


        [NoCache]
        public async Task<ActionResult> Index(string email)
        {
            string email_decrypt = Base64Decode(email);

            user.email = email_decrypt;

            if (fireStoreDb == null)
                ligacaoBD();

            
            // will check the user status
            // if true then the form will not appear
            DocumentReference docRef = fireStoreDb.Collection("users").Document(user.email);
            DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Console.WriteLine("Document data for {0} document:", snapshot.Id);

                User user1 = snapshot.ConvertTo<User>();

                Console.WriteLine("Estado: ", user1.estado);

                user.estado = user1.estado;

                // will store user data temporarily
                TempData["user"] = user;

                if (user.estado)
                    return RedirectToAction("Error", "Home");
            }
            else
            {
                Console.WriteLine("Document {0} does not exist!", snapshot.Id);
            }

            return View(user);
        }


        // method called to create a new password
        [HttpPost]
        public  async Task<ActionResult> ChangePassword(string password)
        {
            //get data
            User user1 = TempData["user"] as User;
            if (user1 != null)
            {
                user = user1;

                user.password = password;
                user.password1 = password;
            }

            // if the status is false then change the password
            if (!user.estado)
            {
                return await change_password();
            }

            return Json(new { redirectToUrl = Url.Action("ErrorUpdate", "Home") });
        }


        //convert string para base 64
        public static string base64Encode(string sData) // Encode    
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

        //convert base64 para string
        public static string Base64Decode(string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }

        
        // method for changing the password
        public async Task<ActionResult> change_password()
        {

            try
            {
                // Initialize the default app
                var defaultApp = FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.GetApplicationDefault(),
                });

                // Retrieve services by passing the defaultApp variable...
                var defaultAuth = FirebaseAdmin.Auth.FirebaseAuth.GetAuth(defaultApp);

                // ... or use the equivalent shorthand notation
                defaultAuth = FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance;
               
            // change the password on user in firebase authentication

                userRecord = await defaultAuth.GetUserByEmailAsync(user.email);


                if (userRecord != null)
                {

                    UserRecordArgs args = new UserRecordArgs()
                    {
                        Uid = userRecord.Uid,
                        Email = user.email,
                        Password = user.password,
                    };

                    UserRecord userRecord1 = await defaultAuth.UpdateUserAsync(args);


                    if (userRecord1 != null)
                    {
                        // change the user password in the bd
                        // encrypt password 

                        string pass_encrypt = base64Encode(user.password);


                        if (fireStoreDb == null)
                            ligacaoBD();


                        //udpate password
                        DocumentReference Ref = fireStoreDb.Collection("users").Document(user.email);
                        Dictionary<string, object> updates = new Dictionary<string, object>
                        {
                            { "password", pass_encrypt },
                            { "estado", true }
                        };

                        user.estado = true;

                        await Ref.UpdateAsync(updates);


                        defaultApp.Delete();

                        //return RedirectToAction("Updated", "Home");
                        return Json(new { redirectToUrl = Url.Action("Updated", "Home") });
                    }
                }

            }
            catch (FirebaseAdmin.Auth.FirebaseAuthException e)
            {
                // return RedirectToAction("ErrorUpdate", "Home");
                return Json(new { redirectToUrl = Url.Action("ErrorUpdate", "Home") });
            }
            catch (FirebaseException e)
            {
                //return RedirectToAction("ErrorUpdate", "Home");
                return Json(new { redirectToUrl = Url.Action("ErrorUpdate", "Home") });
            }

            catch (Exception e)
            {
                //return RedirectToAction("ErrorUpdate", "Home");
                return Json(new { redirectToUrl = Url.Action("ErrorUpdate", "Home") });
            }

            //return RedirectToAction("ErrorUpdate", "Home");
            return Json(new { redirectToUrl = Url.Action("ErrorUpdate", "Home") });
        }

        // method called when the time to create a new password is over
        [HttpPost]
        public ActionResult MyAction()
        {
            Console.Write("Alterou o estado!");

            if (fireStoreDb == null)
                ligacaoBD();

            User user1 = TempData["user"] as User;

            if (user1 != null)
            {
                
                // update user state in bd to true
                DocumentReference Ref = fireStoreDb.Collection("users").Document(user1.email);
                Dictionary<string, object> updates = new Dictionary<string, object>
                {
                  { "estado",true}
                };

                user.estado = true;

                Ref.UpdateAsync(updates);
            }

            return Json(new { redirectToUrl = Url.Action("Error", "Home") });
        }

        // method to call the "Error" page
        public ActionResult Error()
        {
            return View();
        }
        // method to call the "Updated" page
        public ActionResult Updated()
        {
            return View();
        }
        // method to call the "ErrorUpdate" page
        public ActionResult ErrorUpdate()
        {
            return View();
        }
    }

Route Config

 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Views

Error

    <html>
<body>
    <div class="form-group" style="text-align:center">
        <h4>This link is no longer available</h4><br />
    </div>
</body>
</html>

ErrorUpdate

    <html>
<body>
    <div class="form-group" style="text-align:center">
        <h4>Error doing the update. Try again</h4><br />
    </div>
</body>
</html>

Updated

    <html>
<body>
    <div class="form-group" style="text-align:center">
        <h4>Password Updated</h4><br />
    </div>
</body>
</html>

Error:

在此处输入图片说明

I am going to assume that this is .Net Framework

In your controller I have omitted your code just to prove the password is getting in as per the image below

[HttpPost]
public ActionResult ChangePassword(string password)
{
    //get data
    return Json(new { Password = password });
}

在此处输入图片说明

Your Ajax code needs to be something like this too

var jsonObject = {
    password: "mypassword"
};

$.ajax({
    type: "POST",
    url: "Home/ChangePassword",
    data: JSON.stringify(jsonObject),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
         console.log("My Result");
         console.log(result)
    },
    error: function (result) {
        console.log(result);


    }
});

在此处输入图片说明

Note, the ajax code was coming from a page in the home series of views. If you are calling from another location you will need to qualify the path better.

-----Edit-----

After pulling the repo we have seen that this works with the ajax code implementation. The issue now is the IIS implementation and how it is being accessed which is outside the scope of this question

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM