我正在尝试在我的 asp.net core Web 应用程序中使用 HttpContext.Session 但遇到麻烦。访问会话会导致 InvalidOperationException,并显示消息“尚未为此应用程序或请求配置会话”。
我四处搜索,您必须添加一些代码才能启动,即添加会话并使用它。(我还添加了 Nuget 包 AspNetCore.Session)。
现在,当我尝试在 PageModel 代码隐藏中访问 Session (HttpContext.Session) 时。它抛出异常并显示上面段落中指定的消息。除了你必须在我已经完成的启动代码中进行设置之外,我找不到更多详细信息。我的启动代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddHttpClient();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDistributedMemoryCache();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment 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.UseCookiePolicy();
app.UseSession();
app.UseMvc();
}
帖子上的页面模型是我尝试访问它的方式:
public async void OnPostAsync()
{
//Some async stuff here.
//Session throws exception
HttpContext.Session.SetString("something", "something");
}
一只甜甜圈
相关分类