【问题标题】:Cannot apply indexing with [] to an expression of type IConfiguration无法将带有 [] 的索引应用于 IConfiguration 类型的表达式
【发布时间】:2019-03-20 06:21:57
【问题描述】:

我一直在尝试解决这个问题,但现在什么都没有想到...... 使用令牌的 Web 应用程序,但有些东西让我退缩了。

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));

这是整个代码:

 namespace DutchTreat.Controllers
{
    public class AccountController : Controller
    {
        private readonly ILogger<AccountController> _logger;
        private readonly SignInManager<StoreUser> _signInManager;
        private readonly UserManager<StoreUser> _userManager;
        private readonly IConfiguration _config;

        public AccountController(ILogger<AccountController> logger, SignInManager<StoreUser> signInManager, UserManager<StoreUser> userManager, IConfiguration config)
        {
            _logger = logger;
            _signInManager = signInManager;
            _userManager = userManager;
            _config = config;
        }
        public IActionResult Login()
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "App");
            }
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false);
                if (result.Succeeded)
                {
                    if (Request.Query.Keys.Contains("ReturnUrl"))
                    {
                        return Redirect(Request.Query["ReturnUrl"].First());
                    }
                    else
                    {
                        return RedirectToAction("Shop", "App");
                    }
                }
            }

            ModelState.AddModelError("", "Failed to login");

            return View();
        }

        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "App");
        }

        [HttpPost]
        public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.UserName);
                if (user != null)
                {
                    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
                    if (result.Succeeded)
                    {
                        //Create the token
                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                            new Claim(JwtRegisteredClaimNames.Jti, new Guid().ToString()),
                        };

                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                    }
                }

            }

            return BadRequest();
        }
    }
}

【问题讨论】:

  • 错误信息似乎相当清楚——IController不支持索引,所以你不能做_config["Tokens:Key"]
  • 我知道这意味着什么,但我正在关注视频课程,如果他们能做到,我怎么做不到?
  • 你能去定义'IConfiguration',当光标在它上面的时候按F12。分享这些信息?还分享您如何在 Startup.cs 中设置依赖容器?

标签: c# .net token


【解决方案1】:

例外是告诉您不能将索引 ([]) 与 IConfiguration 一起使用

您是在寻找_config.Item["Tokens:Key"] 吗?

MSDN

【讨论】:

  • 它返回 IConfiguration 不包含 Item 的定义,并且没有可访问的扩展方法 Item 接受 IConfiguration 类型的第一个参数...我正在观看的视频使用我编写的语法并且它有效对他们来说......我只是不明白。
【解决方案2】:

如果这是 .NET Core,则有一个 GetValue&lt;T&gt;() 函数,或者如果你想默认为一个字符串,则有一个 GetValue() 函数。

我使用这个,因为我得到了同样的错误。

参考这里MSDN

但是在您的情况下它的基本用法是:

_config.GetValue&lt;string&gt;("Token:Key")

_config.GetValue("Token:Key")

【讨论】:

  • 非常感谢!!解决了!
  • 请记住将此标记为正确答案,欢迎您,很高兴我能提供帮助
【解决方案3】:

_config.Item["Tokens:Key"] 几乎是合法的任务,错误似乎是 Iconfiguration 引用 AutoMapper.Configuration 而不是 Microsoft.Extensions.Configuration

【讨论】:

  • 糟糕的参考资料正是我的情况!!
  • 我正在做同样的课程,这正是问题的答案。
  • 这应该是公认的答案。出于某种原因注入 Iconfiguration Visual Studio 时默认为 automapper。不是你所期望的。
  • 我同意@Mike,这是一个细微的 VS 配置差异,标记为正确答案很重要。
【解决方案4】:

我也遵循同样的方法 检查您的 using 语句并确保您的 IConfiguration 来自

Microsoft.Extensions.Configuration

而不是来自

Automapper.配置

【讨论】:

    【解决方案5】:

    我发布此内容是因为如果您不小心在 dotnet 核心中为 IConfiguration 使用了错误的命名空间,您最终可能会在此处收到完全相同的错误消息。

    使用: using Microsoft.Extensions.Configuration;

    而不是: using Castle.Core.Configuration;

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      相关资源
      最近更新 更多