Search code examples
c#asp.netdto

Adding new field to an object


I am new to c# and .net api. I am doing a login method where if a user is found in database, it will return the user.The user object is likethis,

{ email: user@email.com, password: password, name: User Name, }

First thing, I want to remove the password from the return object, second I want to add the JWT token to the return object. Here is my code:

    public object LoginCurrentUser(User user) {
        var result = AuthenticateUser(user);

        if (result != null)
        {
            var token = Generate(user);

       //I want to create new variable here that removes the password and adds the token to the field.

            return result;
        }
        else {
            return null;
        }

    }

Solution

  • It should be pretty straight forward.

    if (result != null)
    {
        var token = Generate(user);
    
        var response = new {
            Email = result.Email,
            Name = result.Name,
            Token = token
        };
    
        return response;
    }
    

    Alternatively, You can create a DTO class for the response and return its object.