Injecting Iconfiguration into Controller in Webapi project

Asked

Viewed 50 times

0

I’m developing an API, and I’m implementing JWT on it, I made a Controller to manage the Token and Login but when I inject the interface IConfiguration and the application tells me that I have to register her.

My question is it no longer comes registered by default.

Follows my code.

 public class Startup
{
    private Container _container { get; set; }
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        _container = ContainerConfig.SimpleInjectorDependencyResolver();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // Configurações Swagger
        services.AddSwaggerGen(x => {
            x.SwaggerDoc("v1", new Info() {
                Title = "Headbit.Framework",
                Version = "v1",
                Description = "A simple example ASP.NET Core Web API",
                TermsOfService = "https://example.com/termos"
            });
        });

        // Configurações do JWT (Json Web Token)
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
             {
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuer = true,
                     ValidateAudience = true,
                     ValidateLifetime = true,
                     ValidateIssuerSigningKey = true,
                     ValidIssuer = Configuration["Jwt:Issuer"],
                     ValidAudience = Configuration["Jwt:Audience"],
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                 };
             });

        services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(_container));
        services.AddSingleton<IConfiguration>(Configuration);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute("default", "{controller=Seguranca}/{action=Login}");
        });

        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Headbit.Framework");
        });

        _container.RegisterMvcControllers(app);
        _container.Verify();
    }
}

Follows the code of Controller where gives the error that is not registered the interface

 [Route("api/v1/[controller]/[action]")]
[ApiController]
public class SegurancaController : ControllerBase
{
    private IConfiguration _config;

    public SegurancaController(IConfiguration Configuration)
    {
        _config = Configuration;
    }

    public IActionResult Login([FromBody]PessoaVm entity)
    {
        bool resultado = ValidaUsuario(entity);

        if (resultado)
        {
            var tokenString = GeraToken();
            return Ok(new { token = tokenString });
        }
        else
        {
            return Unauthorized();
        }
    }

    private string GeraToken()
    {
        var issuer = _config["Jwt:Issuer"];
        var audience = _config["Jwt:Audience"];
        var expiry = DateTime.Now.AddMinutes(120);
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(issuer: issuer, audience: audience, expires: expiry, signingCredentials: credentials);
        var tokenHandler = new JwtSecurityTokenHandler();
        var stringToken = tokenHandler.WriteToken(token);
        return "";
    }

    private bool ValidaUsuario(PessoaVm entity)
    {
        if (entity.Usuario == "rodrigo" && entity.Senha == "rodrigo")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Important note: I’m following this example:

http://www.macoratti.net/19/04/aspncore_jwt1.htm

  • puts the error stacktrace for kindness

1 answer

0

Good afternoon!

I believe it’s in those lines:

 public class Startup
{
    private Container _container { get; set; }
    public IConfiguration Configuration { get; }

Try switching to the code below:

public static IConfiguration Configuration { get; set; }

If this is not a problem, refer to Configuration.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.