#c# #ajax #asp.net-mvc
#c# #ajax #asp.net-mvc
Вопрос:
Я разрабатываю веб-страницу в ASP.NET MVC. Страница позволяет создать новый пароль. После того, как пользователь заполнит данные в форме и нажмет на кнопку «Изменить пароль», пароль будет изменен в firebase. Когда я запускаю страницу в обычном режиме (localhost), она работает отлично. Но когда я пытаюсь получить доступ по 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 amp;amp; seconds <= 9) {
document.getElementById('time-left').innerHTML = '0' minutes ':0' seconds;
}
else if (seconds <= 9 amp;amp; 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 == "" amp;amp; 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 amp;amp; 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 amp;amp; 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">amp;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");
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>
Ошибка:
Комментарии:
1. Пожалуйста, имейте весь файл C # и View File целиком, чтобы я мог помочь вам с этим
2. если вы попытаетесь вызвать прямой http://<ipaddress>/Home/ChangePassword и у вас будет точка останова на месте. Вы достигли точки останова? Возможно, стоит попробовать это в POSTMAN или Fiddler, чтобы вы могли соответствующим образом управлять вызовом. Кроме того, вам не обязательно публиковать полный файл c #. вам просто нужно опубликовать соответствующий метод, функцию javascript и вызов ajax, которые имеют отношение к этому сообщению.
3. Также является ли это .Net Framework или Core?
4. @Simon Price .Net Framework. Но я попробую с почтальоном
Ответ №1:
Я собираюсь предположить, что это .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 и способах доступа к нему, что выходит за рамки этого вопроса
Комментарии:
1. Понял. Я изменил ajax на то, что у вас было, и теперь мне представляется это: ссылка , как показано в Postman
2. эта ссылка говорит мне, что мне нужен доступ, что вы видите?
3. Прошу прощения. Я думаю, теперь вы можете увидеть ссылку
4. попробуйте с этим
url: "Home/ChangePassword", instead then
5. Где по отношению к вашему javascript ваше мнение? это в том же представлении или в папке scripts?