Anil
Anil

Reputation: 47

Asp.Net Core 2 Web API 500 internal server error

when I try to access the API via Postman,

Send:

localhost:5050/api/Auth/token

Body:

{ "UserName": "jouverc", "Password": "P@ssw0rd!" }

to this method:

[Produces("application/json")]
[Route("api/Auth")]
public class AuthController : Controller
{

    #region constructor injection

    private readonly IPasswordHasher<User> _hasher;
    private readonly UserManager<User> _userManager;
    private readonly IConfigurationRoot _config;
    private readonly SignInManager<User> _signInManager;

    public AuthController(IPasswordHasher<User> hasher, UserManager<User> userManager, SignInManager<User> signInManager, IConfigurationRoot config)
    {
        _hasher = hasher;
        _userManager = userManager;
        _signInManager = signInManager;
        _config = config;
    }

        #endregion

    #region createToken

    [HttpPost("token")]
    public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(model.UserName); 
            if (user != null) 
            {
                if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)  
                {
                    return Ok(CreateToken(user)); 
                }
            }
        }
        catch (Exception)
        {
            //log 
        }
        return null;
    }

    private async Task<JwtPacket> CreateToken(User user)
    {
        var userClaims = await _userManager.GetClaimsAsync(user); 

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.UserName), 
            new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) 
        }.Union(userClaims);


        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); 
        var token = new JwtSecurityToken(issuer: _config["Tokens:Issuer"], 
            audience: _config["Tokens:Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddDays(2),
            signingCredentials: cred
        );
        return new JwtPacket
        {
            Token = new JwtSecurityTokenHandler().WriteToken(token),
            Expiration = token.ValidTo.ToString(),
            UserName = user.UserName
        };

    }

    public class JwtPacket
    {
        public string Token;
        public string UserName;
        public string Expiration;
    }

    #endregion

}

I receive a 500 Internal Server Error:

Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfigurationRoot' while attempting to activate 'WebAPI.Controllers.AuthController

how should i configurate the Startup?

 public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.

Upvotes: 0

Views: 3415

Answers (3)

Ryan Dobbs
Ryan Dobbs

Reputation: 381

Just change IConfigurationRoot to IConfiguration on the constructor for the controller.

But what might be better is to use the IOpions pattern for injecting settings into your controller.

Upvotes: 0

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16856

If you are just reading values from the appsettings.json then use the IConfiguration interface instead.

Here's how to implement it in the Startup class

public Startup(IApplicationEnvironment appEnv)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddEnvironmentVariables()
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfiguration>(Configuration);
}

Upvotes: 0

Anton Toshik
Anton Toshik

Reputation: 2929

In .net core 2.0

IConfigurationRoot is now just IConfiguration.

Explained in this document: Migrating from 1.x to 2.0.

In 2.0 projects, the boilerplate configuration code inherent to 1.x projects runs behind-the-scenes. For example, environment variables and app settings are loaded at startup. The equivalent Startup.cs code is reduced to IConfiguration initialization with the injected instance:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

Upvotes: 2

Related Questions