簡體   English   中英

如何在 asp.net core razorpage 的布局頁面中接收 cookie?

[英]How can I receive cookie in layout page in asp.net core razorpage?

我在 asp.net 核心 RazorPage 創建登錄頁面,下面的代碼是: 登錄頁面:

 List<Claim> claims = new List<Claim>()
            {
                new Claim("Test","Test"),
                new Claim(ClaimTypes.NameIdentifier as string,user.UserID.ToString()  as string),
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim(ClaimTypes.Role as string,user.UserRole.ToString() as string)
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimPrincipal = new ClaimsPrincipal(identity);
            HttpContext.SignInAsync(claimPrincipal);
            return RedirectToPage("../Index");

我的 _layout 頁面是這樣的 _Layout:

                if (???????????)
                    {
                        <div>@User.Identity.Name</div>
                        <ul class="navbar-nav d-flex justify-content-end">
                            <li class="nav-item">
                                <a class="btn btn-primary" asp-page="/Auth/Logout">Logout</a>
                            </li>
                        </ul>
                    }
                    else
                    {
                        <ul class="navbar-nav d-flex justify-content-end flex-grow-1">
                            <li class="nav-item">
                                <a class="btn btn-primary" asp-page="/Auth/login">Login</a>
                            </li>
                            <li class="nav-item">
                                <a class="btn" asp-page="/Auth/Register">Register</a>
                            </li>
                        </ul>
                    }

問題是:我應該用什么代替問號?

判斷用戶是否登錄成功,

在 _layout 中嘗試以下代碼:

@if (User.Identity.IsAuthenticated)

在我的startup.cs

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();

結果:

在此處輸入圖像描述

這是我的 program.cs(我使用 .net core 6),我是 .net core 的新手

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PageNamaProj.Context;
using PageNamaProj.Services.Users;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddHttpContextAccessor();

builder.Services.AddAuthorization(option =>
{
    option.AddPolicy("Account", builder =>
    {
        builder.RequireAuthenticatedUser();
    });
});

builder.Services.AddRazorPages()
    //.AddRazorRuntimeCompilation()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AuthorizeFolder("/Profile", "Account");
    });

builder.Services.AddScoped<IUserService, UserService>();


builder.Services.AddDbContext<TablesContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));


builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(option =>
{
    option.LoginPath = "/Auth/Login";
    option.LogoutPath = "/Auth/Logout";
    option.ExpireTimeSpan = TimeSpan.FromDays(30);
});


builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<TablesContext>();


var app = builder.Build();

//Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.Use(async (context, next) =>
{
    var token = context.Request.Cookies["Token"]?.ToString();
    if (string.IsNullOrWhiteSpace(token) == false)
    {
        context.Request.Headers.Append("Authorization", $"Bearer {token}");
    }
    await next();
});


app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.Use(async (context, next) =>
{
    await next();
    var status = context.Response.StatusCode;
    if (status == 401)
    {
        var path = context.Request.Path;
        context.Response.Redirect($"/login?redirectTo={path}");
    }
});
app.UseAuthentication();

app.UseAuthorization();
app.MapRazorPages();
app.Run();

@QingGuo 你的代碼是真的。 我的問題是另一個代碼謝謝你的回答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM