[英]how to pass value from one controller to another controller in .netcore
Logged User Id stored into another table.记录的用户 ID 存储到另一个表中。 How to Pass the Login UserId to the another controller.
如何将登录用户 ID 传递给另一个 controller。 ** public async Task Login([FromBody] LoginModel model) {
** 公共异步任务登录([FromBody] LoginModel 模型){
var user = await userManager.FindByNameAsync(model.Username);
if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
{
var userRoles = await userManager.GetRolesAsync(user);
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
foreach (var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.Now.AddDays(3),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
username=user.UserName,
expiration = token.ValidTo
});
}
return Unauthorized();
}
Login **
You can use Temp Data:您可以使用临时数据:
TempData["UserID"] = user.ID;
In a different controller:在不同的 controller 中:
var userID = TempData["UserID"];
Using session:使用 session:
Configure session state in startup class:在启动 class 中配置 session state:
In ConfigureServices:在配置服务中:
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
In confugure:在配置中:
app.UseSession();
Define a string定义一个字符串
public const string SessionUserId = string.Empty();
We set a string我们设置一个字符串
if(string.IsNullOrEmpty(HttpContext.Session.GetString(SessionUserId))) HttpContext.Session.SetString(SessionUserId, user.ID.ToString());
We can get defined string:我们可以得到定义的字符串:
var name = HttpContext.Session.GetString(SessionUserId);
More info in documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0文档中的更多信息: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.