【发布时间】:2022-01-01 06:55:08
【问题描述】:
我想访问另一个类中的配置变量的值。
这里是 appsetting.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Configurations": {
"FirstVerificationValidationDurationMinutes": 2,
"ResendedVerificationValidationDurationMinutes": 2,
"JwtRegisterTokenValidationDurationMinutes": 30,
"JwtLoginTokenValidationDurationMinutes": 30
}
}
在这里,我想在下面的类中使用 JwtLoginTokenValidationDurationMinutes 的值(如上所示,在 appsettings.json 中声明):
public async Task<UserCredentialDto> JwtAuthentication(UserCredentialViewModel userCredential)
{
var user = await _userService.LoginUser(userCredential);
if (user is null)
{
return new UserCredentialDto
{
Status = new StatusMaker().ErrorStatus(user.Status.Message)
};
}
//TODO
var _key = "This is for test";
var tokenHandler = new JwtSecurityTokenHandler();
var tokenKey = Encoding.ASCII.GetBytes(_key);
//var tokenValidationDuration = HERE I NEED THE VALUE //HOW TO ACCESS VALUES FROM appsettings.json?
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(/*tokenValidationDuration*/),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(tokenKey),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new UserCredentialDto
{
Token = tokenHandler.WriteToken(token)
};
}
}
那么如何从 appsettings.json 访问值?
我尝试使用 Microsoft.Extensions.Configuration,但它似乎在 .Net 6 中不存在。
【问题讨论】:
-
@gsharp 不,不是
-
@Masoud 看看我的问题:stackoverflow.com/questions/69390676/…
-
@sajed 不,这不是答案☺
-
@Masoud 为什么不呢?