ASP.NET Core: передача входа в сеанс/аутентификацию в localStorageC#

Место общения программистов C#
Ответить
Anonymous
 ASP.NET Core: передача входа в сеанс/аутентификацию в localStorage

Сообщение Anonymous »

Я пытаюсь передать адрес электронной почты и имя пользователя в 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.GetString("UserEmail");
HttpContext.Session.GetString("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;
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.");
}


Я могу сохранить файл cookie, но не сеанс или локальное хранилище.
[img]https:// i.sstatic.net/6RKcqMBM.png[/img]

и это моя программа.cs
using Microsoft.EntityFrameworkCore;
using Auth.Data; // Reference to your Data folder

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Add session management services with some configuration for session timeout, etc.
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeout duration
options.Cookie.HttpOnly = true; // Make session cookies HTTP-only for security
options.Cookie.IsEssential = true; // Ensure session cookie is available even if GDPR opt-out is active
});

// Add database context using MySQL
builder.Services.AddDbContext(options =>
options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection"))));

var app = builder.Build();

// Use session middleware, which is necessary for session management
app.UseSession();
...


Подробнее здесь: https://stackoverflow.com/questions/790 ... calstorage
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»