Мне не удается заставить сеанс работать.
Когда я пытаюсь получить доступ к экземпляру сеанса на странице через:
HttpContext.Session.Set("JWToken", Encoding.ASCII.GetBytes(user.Token));
Я получаю это:
System.InvalidOperationException: Сессия не была настроена для этого приложения или запроса.
Я думаю, что настроил ее правильно ....
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<DatabaseContext>();
byte[] key = Encoding.UTF8.GetBytes("SUPERSECRETKEYFORJWT");
services.AddJwtBearerAuthentication(key);
services.AddScoped<IAuthenticationService<User>, UserService>();
services.AddMvc()
.SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0)
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Logout");
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = ".supportcockpit";
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
// Make the session cookie essential
options.Cookie.IsEssential = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
app.Use(async (context, next) =>
{
Trace.WriteLine("call to middleware");
if (context.Session.TryGetValue("JWToken", out byte[] tokenBytes))
{
string token = Encoding.ASCII.GetString(tokenBytes);
context.Request.Headers.Add("Authorization", "Bearer " + token);
}
await next();
});
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
}