【发布时间】:2020-08-25 20:01:33
【问题描述】:
我正在用 ASP.NET MVC 开发一个网页。该页面允许您创建新密码。用户在表单上填写数据并点击“更改密码”按钮后,将在firebase中更改密码。 当我正常运行页面(本地主机)时,它运行良好。但是当我尝试通过 ip 访问并单击按钮时,它什么也没做。 检查后,我意识到有一个 POST 错误。但它并没有确切说明它失败的地方。我怎么知道它失败的确切线路?或者也许有人可以帮助我编写代码。 感谢任何帮助的人 我的代码:
索引.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");
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();
}
}
路由配置
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>
错误:
【问题讨论】:
-
请提供完整的 C# 文件和查看文件,以便我可以帮助您解决此问题
-
如果您尝试直接调用 http://
/Home/ChangePassword 并设置断点。你打断点了吗?可能值得在 POSTMAN 或 Fiddler 中尝试此操作,以便您可以相应地控制调用。此外,您不需要发布完整的 c# 文件。您只需要发布与此帖子相关的相关方法以及 javascript 函数和 ajax 调用。 -
这也是.Net Framework还是Core?
-
@Simon Price .Net 框架。但我会和邮递员一起尝试
标签: c# ajax asp.net-mvc