如何解决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">×</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>
错误:
解决方法
我将假定这是.Net Framework
在您的控制器中,我只是为了证明密码如下图所示已省略了您的代码
[HttpPost]
public ActionResult ChangePassword(string password)
{
//get data
return Json(new { Password = password });
}
您的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);
}
});
请注意,ajax代码来自家庭视图系列中的一个页面。如果您是从其他位置拨打电话,则需要更好地限定路径。
-----编辑-----
拉回仓库后,我们已经看到它可以与ajax代码实现一起使用。现在的问题是IIS的实现以及如何访问它,这超出了此问题的范围
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。