0

I have this code in ASP.NET Core Web API:

DTO:

public class AuthRequest
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class AuthResponse
{
    public string Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Token { get; set; }
}

Services:

public interface IAuthService
{
    Task<AuthResponse> Login(AuthRequest request);
}

public async Task<AuthResponse> Login(AuthRequest request)
{
    var user = await _userManager.FindByEmailAsync(request.Email);

    if (user == null)
    {
        throw new Exception($"User with {request.Email} not found.");
    }

    var result = await _signInManager.PasswordSignInAsync(user.UserName, request.Password, false, lockoutOnFailure: false);

    if (!result.Succeeded)
    {
        throw new Exception($"Credentials for '{request.Email} aren't valid'.");
    }

    JwtSecurityToken jwtSecurityToken = await GenerateToken(user);
    var roles = await _userManager.GetRolesAsync(user);

    AuthResponse response = new AuthResponse
    {
        Id = user.Id,
        Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
        Email = user.Email,
        UserName = user.UserName,
        roles,
    };

    return response;
}

From the code above, I want to include roles of the logged in user in the AuthResponse. So I added, roles

But I got this error:

Error CS0747 Invalid initializer member declarator

roles is highlighted.

How do I resolve this?

Thanks

1
  • I'm not sure to understand... did you added the Roles property in the AuthResponse model class? Commented Mar 23, 2022 at 13:35

1 Answer 1

2

Notice how this property initialization:

roles,

differs from the rest:

Id = user.Id,
Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
Email = user.Email,
UserName = user.UserName,

You need to specify which property is being set. For example, is there a Roles property (which matches the type)? If so, it would be something like this:

Roles = roles,

Basically, whatever property you're trying to initialize in the resulting object, you need to indicate the name of that property in its initialization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.