ASP.NET MVC失败的AJAX发布请求

如何解决ASP.NET MVC失败的AJAX发布请求

我正在ASP.NET MVC中开发一个网页。该页面允许您创建新密码。用户填写表单上的数据并单击“更改密码”按钮后,密码将在Firebase中更改。 当我正常运行页面(本地主机)时,它可以正常运行。但是,当我尝试通过ip访问并单击按钮时,它什么也没做。 检查后,我意识到存在POST错误。但是它并没有确切说明失败的地方。我怎么知道发生故障的确切路线?也许有人可以帮助我编写代码。 感谢任何人的帮助 我的代码:

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>

控制器

 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") });
            }

            catch (Exception e)
            {
                //return RedirectToAction("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>
                {
                  { "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();
        }
    }

路由配置

 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 }
            );
        }
    }

观看次数

错误

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

错误更新

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

已更新

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

错误:

enter image description here

解决方法

我将假定这是.Net Framework

在您的控制器中,我只是为了证明密码如下图所示已省略了您的代码

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

enter image description here

您的Ajax代码也必须是这样的

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);


    }
});

enter image description here

请注意,ajax代码来自家庭视图系列中的一个页面。如果您是从其他位置拨打电话,则需要更好地限定路径。

-----编辑-----

拉回仓库后,我们已经看到它可以与ajax代码实现一起使用。现在的问题是IIS的实现以及如何访问它,这超出了此问题的范围

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res