You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core登录后无法将用户信息存入localStorage求助

解决方案:ASP.NET Core登录后将用户信息存入localStorage

核心逻辑

localStorage是浏览器端专属存储,只能通过前端JavaScript操作,后端(ASP.NET Core)无法直接写入。解决思路是:登录成功后后端把用户信息传递给前端,再由前端JS写入localStorage。

针对两种方案的修正方案

方案1:AJAX提交+返回JSON(支持存localStorage+跳转)

修改AuthController的登录接口,验证通过后返回用户信息和跳转地址:

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid && ValidateUser(model.Email, model.Password))
    {
        // 生成认证Cookie(保留原有后端认证逻辑)
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Email, model.Email),
            new Claim(ClaimTypes.Name, model.Username)
        };
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

        // 返回用户信息给前端
        return Json(new { success = true, email = model.Email, username = model.Username, redirectUrl = "/Dashboard" });
    }
    return Json(new { success = false, message = "账号或密码错误" });
}

修改Login.cshtml的表单提交逻辑,用AJAX处理并写入localStorage:

<form id="loginForm">
    <input type="email" name="Email" required>
    <input type="password" name="Password" required>
    <button type="submit">登录</button>
</form>

<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    const response = await fetch('/Auth/Login', {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });

    const result = await response.json();
    if (result.success) {
        // 存入localStorage
        localStorage.setItem('userEmail', result.email);
        localStorage.setItem('username', result.username);
        // 跳转到仪表板
        window.location.href = result.redirectUrl;
    } else {
        alert(result.message);
    }
});
</script>

方案2:后端跳转后在仪表板注入信息

如果保留后端跳转逻辑,登录成功后跳转到仪表板,再在页面中注入用户信息并写入localStorage:

AuthController登录逻辑(保持跳转逻辑):

[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
    if (ModelState.IsValid && ValidateUser(model.Email, model.Password))
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Email, model.Email),
            new Claim(ClaimTypes.Name, model.Username)
        };
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

        return RedirectToAction("Index", "Dashboard");
    }
    ModelState.AddModelError("", "账号或密码错误");
    return View(model);
}

Dashboard/Index.cshtml中注入用户信息并写入localStorage:

@{
    var userEmail = User.FindFirstValue(ClaimTypes.Email);
    var username = User.FindFirstValue(ClaimTypes.Name);
}

<script>
window.addEventListener('load', () => {
    localStorage.setItem('userEmail', '@userEmail');
    localStorage.setItem('username', '@username');
});
</script>

登出功能实现

登出时需同时清除localStorage和后端认证Cookie:

后端登出接口

[HttpPost]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Json(new { success = true, redirectUrl = "/Auth/Login" });
}

前端登出按钮逻辑

<button id="logoutBtn">登出</button>

<script>
document.getElementById('logoutBtn').addEventListener('click', async () => {
    const response = await fetch('/Auth/Logout', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'RequestVerificationToken': '@Html.AntiForgeryToken()'
        }
    });
    const result = await response.json();
    if (result.success) {
        localStorage.removeItem('userEmail');
        localStorage.removeItem('username');
        window.location.href = result.redirectUrl;
    }
});
</script>

Program.cs关键配置检查

确保已正确启用Cookie认证,且中间件顺序正确:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

// 配置Cookie认证
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Auth/Login";
        options.LogoutPath = "/Auth/Logout";
        options.ExpireTimeSpan = TimeSpan.FromHours(8);
    });

var app = builder.Build();

// 中间件顺序:认证→授权→路由→端点
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

内容的提问来源于stack exchange,提问作者Xenex Ashura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:25:06