【问题标题】:'IConfiguration' does not contain a definition for 'GetSection'“IConfiguration”不包含“GetSection”的定义
【发布时间】:2021-08-03 14:12:25
【问题描述】:

我正在尝试使用 .Net 5 向 Web api 添加身份验证,但在创建令牌的方法中出现上述错误。

private string CreateToken(User user)
    {
        List<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.Username)
        };

        // The underlined error is on the line below on the GetSection method.
        SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));

        SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = creds
        };

        JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
        SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);
    }

我之前在以前的项目中做过这个,效果很好。在相同版本的.Net中添加了相同的包。

不知道还有什么可能导致这种情况。

谢谢。

【问题讨论】:

  • 那是来自Microsoft.Extensions.ConfigurationIConfiguration 吗?
  • 这个小问题让我解决了问题。我没有意识到我正在使用 AutoMapper.Configuration 进行调用;而不是 Microsoft.Extensions.Configuration。不管怎样,谢谢你! :)
  • IConfiguration 来自 Microsoft.Extensions.Configuration.Abstractions 命名空间,所以安装它应该可以工作
  • 只需将库从 Automapper.Configuration 更改为 Microsoft.Extensions.Configuration。不需要安装其他任何东西。

标签: c# .net jwt


【解决方案1】:

IConfiguration 接口应该来自Microsoft.Extensions.Configuration 库。

在这种情况下,IConfiguration 接口是来自 AutoMapper.Configuration 的定义。

由于IOptions&lt;&gt;,可能还需要Microsoft.Extensions.Options.ConfigurationExtensions 库。

【讨论】:

  • 没错。当我使用编译器插入库时,我必须偶然添加 Automapper.Configuration。当有人在上面的 cmets 上问我时,我想通了。 Microsoft.Extensions.Configuration 是要添加的正确库,必须删除 Automapper.Configuration。
猜你喜欢
  • 2019-07-13
  • 2023-03-05
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
相关资源
最近更新 更多