下面是我来自startup.cs的代码,
public void ConfigureServices(IServiceCollection services){
services.AddMvc().AddJsonOptions(options =>{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddDistributedMemoryCache();
services.AddSession(options => {
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(36000);
options.Cookie.HttpOnly = true;
});
services.AddCors(options => {
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env{
if (env.IsDevelopment()){
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
//app.UseCors("CorsPolicy");
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseSession();
app.UseAuthentication();
app.UseMvc();
}
以下是在会话中设置和获取用户ID的代码:
HttpContext.Session.SetInt32("UserId", user.Id);
int userId = (int)HttpContext.Session.GetInt32("UserId");
在以不同于设置它的操作读取会话时,我处于异常之下。会话无法正常工作的任何原因?
答案 0 :(得分:0)
此解决方案仅适用于dotnetcore 2.1或更高版本。我的解决方案是dotnetcore 2.0