C# asp.net core 3.1中的操作筛选器中的会话始终为空
我试图在会话中设置一个值,然后想在action filter中检索它,尝试通过actionContext访问,但仍然得到空会话值,无法找出哪里做错了。在我的Authenticate Controller中,我在验证用户凭据后设置会话值C# asp.net core 3.1中的操作筛选器中的会话始终为空,c#,asp.net-web-api,.net-core,jwt,asp.net-core-webapi,C#,Asp.net Web Api,.net Core,Jwt,Asp.net Core Webapi,我试图在会话中设置一个值,然后想在action filter中检索它,尝试通过actionContext访问,但仍然得到空会话值,无法找出哪里做错了。在我的Authenticate Controller中,我在验证用户凭据后设置会话值 public class AuthController : Controller { private IHttpContextAccessor httpContextAccessor { get; } public AuthController (IHtt
public class AuthController : Controller {
private IHttpContextAccessor httpContextAccessor { get; }
public AuthController (IHttpContextAccessor contextAccessor)
{
httpContextAccessor = contextAccessor;
}
private async Task<IActionResult> Login(signIn objDto){
// Some Authenticate Code and token generation
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
new Claim(ClaimTypes.Name,user.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("Jwt:TokenSecretKey").Value));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
httpContextAccessor.HttpContext.Session.SetString("token",token);
//return Ok result with token
}
}
下面是我的创业课程
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers(x => x.Filters.Add(typeof(WebAPIActionFilterHelper))).
AddJsonOptions(o =>
{
o.JsonSerializerOptions.MaxDepth = 999999999;
});
services.AddAutoMapper(typeof(Startup));
services.AddCors();
services.AddHttpContextAccessor();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddAuthorization();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Jwt:TokenSecretKey").Value)),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
};
});
services.AddDistributedMemoryCache();
services.AddSession(opt =>
{
opt.IdleTimeout = TimeSpan.FromMinutes(10);
});
}
// 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();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
公共类启动
{
公共IConfiguration配置{get;}
公共启动(IConfiguration配置)
{
配置=配置;
}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(x=>x.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”));
services.AddControllers(x=>x.Filters.Add(typeof(WebAPIActionFilterHelper)))。
AddJsonOptions(o=>
{
o、 JsonSerializerOptions.MaxDepth=9999999;
});
AddAutoMapper(类型(启动));
services.AddCors();
AddHttpContextAccessor();
services.addScope();
services.AddAuthorization();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt=>
{
opt.TokenValidationParameters=新的TokenValidationParameters
{
ValidateLifetime=true,
ValidateSuersigningKey=true,
IssuerSigningKey=new-SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection(“Jwt:TokenSecretKey”).Value)),
validateisuer=true,
ValidateAudience=true,
ValidIssuer=配置[“Jwt:Issuer”],
Validudience=配置[“Jwt:Issuer”],
};
});
AddDistributedMemoryCache();
services.AddSession(opt=>
{
opt.IdleTimeout=TimeSpan.frommins(10);
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
请查看指南。“我正在设置会话值”的代码至少在帖子中(可能在您的实际程序中)完全缺失。它在我的项目中可以很好地工作。您是如何设置会话的?请确保只使用邮递员或使用其他工具。例如,不要交替使用邮递员和broswer发送请求。@Rena我已经更新了问题。我实际上正在从我的angular应用程序发送请求。您好@ZafeerUlHaq,您是否调试了代码并在操作筛选器中设置断点以检查会话是否为空?请尝试删除操作筛选器中的UnauthorizedResult
,并在传递令牌时检查结果。因为如果您的令牌无效,结果也将是401 unauthorized。您是否介意分享如何使用angular发送请求以及如何生成jwt令牌?@Rena我调试了代码,并快速查看会话值它仍然为空。但是,未授权结果
仅适用于AuthController以外的控制器。我只是尝试处理空闲超时,这就是为什么我将令牌存储在会话中并验证它是否仍在会话中。但是,我已经用JWT令牌生成代码更新了这个问题。在这里,我只是发送一个简单的post请求。请查看指导。“我正在设置会话值”的代码至少在帖子中(可能在您的实际程序中)完全缺失。它在我的项目中可以很好地工作。您是如何设置会话的?请确保只使用邮递员或使用其他工具。例如,不要交替使用邮递员和broswer发送请求。@Rena我已经更新了问题。我实际上正在从我的angular应用程序发送请求。您好@ZafeerUlHaq,您是否调试了代码并在操作筛选器中设置断点以检查会话是否为空?请尝试删除操作筛选器中的UnauthorizedResult
,并在传递令牌时检查结果。因为如果您的令牌无效,结果也将是401 unauthorized。您是否介意分享如何使用angular发送请求以及如何生成jwt令牌?@Rena我调试了代码,并快速查看会话值它仍然为空。但是,未授权结果
仅适用于AuthController以外的控制器。我只是尝试处理空闲超时,这就是为什么我将令牌存储在会话中并验证它是否仍在会话中。但是,我已经用JWT令牌生成代码更新了这个问题。我只是发送一个简单的post请求。
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers(x => x.Filters.Add(typeof(WebAPIActionFilterHelper))).
AddJsonOptions(o =>
{
o.JsonSerializerOptions.MaxDepth = 999999999;
});
services.AddAutoMapper(typeof(Startup));
services.AddCors();
services.AddHttpContextAccessor();
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddAuthorization();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Jwt:TokenSecretKey").Value)),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
};
});
services.AddDistributedMemoryCache();
services.AddSession(opt =>
{
opt.IdleTimeout = TimeSpan.FromMinutes(10);
});
}
// 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();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}