Я пытаюсь передать адрес электронной почты и имя пользователя в localStorage, чтобы использовать их на своей панели управления и выйти из учетной записи. Я не очень хорошо знаком с ASP.NET, поскольку его настройку было слишком сложно найти в Google. Конечно, я использовал ресурсы Chatgpt, чтобы сделать это, но я не могу этого сделать с очень сложными областями.
У меня есть Controller/AuthController.cs, поэтому вы увидите все аутентификация здесь для входа в систему.
Попытка входа №1
Первая попытка — передать Json, но проблема с ним во внешнем интерфейсе при входе в систему. cshtml он не передает localStorageItem, который я хотел передать, а также не перенаправляет.
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
return Json(new { success = false, message = "Invalid login attempt." });
}
var user = _context.Users.FirstOrDefault(u => u.Email == model.Email);
if (user == null || !VerifyPasswordHash(model.Password, user.Password))
{
return Json(new { success = false, message = "Invalid login attempt." });
}
// Store user info in session
HttpContext.Session.SetString("UserEmail", user.Email);
HttpContext.Session.SetString("UserName", user.Username);
// Return a JSON response with user details
return Json(new { success = true, email = user.Email, username = user.Username });
}
.cshtml вид:
document.getElementById('loginButton').addEventListener('click', function () {
// Fetch email and password from the form
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Prepare data to send in POST request
var formData = new FormData();
formData.append('Email', email);
formData.append('Password', password);
// Send AJAX request to login endpoint
fetch('/Authentication/Login', {
method: 'POST',
body: formData
})
.then(response => response.json()) // Parse JSON response
.then(data => {
if (data.success) {
// If login successful, save user data in localStorage
localStorage.setItem('userEmail', data.email);
localStorage.setItem('userName', data.username);
// Log for debugging purposes
console.log("User session saved in localStorage.");
// Optionally, redirect or update UI here
} else {
// Display error message
var loginMessage = document.getElementById('loginMessage');
loginMessage.innerText = data.message;
loginMessage.style.display = 'block';
}
})
.catch(error => {
console.error('Error during login:', error);
});
});
Попытка входа 2
Этот перенаправление работает с информационной панелью, но также не позволяет сохранить локальное хранилище:
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid)
{
// Console.WriteLine("Model state is invalid during login attempt.");
return View("~/Views/Authentication/Login.cshtml", model);
}
var user = _context.Users.FirstOrDefault(u => u.Email == model.Email);
if (user == null || !VerifyPasswordHash(model.Password, user.Password))
{
// Console.WriteLine($"Invalid login attempt for email: {model.Email}");
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View("~/Views/Authentication/Login.cshtml", model);
}
// Store user info in session
HttpContext.Session.SetString("UserEmail", user.Email);
HttpContext.Session.SetString("UserName", user.Username);
// Console.WriteLine($"User {model.Email} logged in successfully.");
// Pass session data to the view via ViewBag
ViewBag.UserEmail = user.Email;
ViewBag.UserName = user.Username;
// return RedirectToAction("Index", "Dashboard");
return RedirectToAction("Index", "Dashboard");
}
.cshtml вид:
// Use ViewBag values passed from the controller
var userEmail = '@ViewBag.UserEmail';
var userName = '@ViewBag.UserName';
if (userEmail && userName) {
// Store session info in localStorage
localStorage.setItem("userEmail", userEmail);
localStorage.setItem("userName", userName);
// Optionally, you can log the stored data
console.log("User session saved in localStorage.");
} else {
console.log("No session data found to save.");
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... calstorage