0

I am creating a REST API so I am creating a controller.

I have an entity like this:

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public int Age { get; set; }
    public string PersonalInformation { get; set; }
}

In my front-end I have 2 views that requires two different models of the User.

An admin can check the personal information of the user and he needs to see all the information except of the password.

A user con modify all his information, so he will need to see all his information.

Another view is to only show the user Username and PersonalInformation and both, admin and user may ask for it.

I this case, I will need three different models to send to the frontend.

To access this information my controller will have a method:

[HttpGet("{id}")]
public IActionResult Get(int id)
{
    ....
}

At this point comes my question, because I have same method to return two different models (in the future may be more). Investigation on Web API design, I read that the keyword to access may no be verbs. One method url will be /users/1, but the others must be different and here comes my problem.

Thanks!

2
  • 1
    You are describing three different endpoints, each of them with a different resource (you may call them DTOs or models). Why don't you just create three different routes then? /users/current, /users/{id} and /personalinfo/{id}? Commented Oct 7, 2018 at 11:28
  • Not a good idea at all... then an admin can call the user endpoint. That is not secure... Commented Oct 7, 2018 at 12:07

1 Answer 1

1

You can create two different dtos (data transfer objects). Just two simple classes like your user with the data you want in it. I don t know how you are doing authorization, but when an admin is calling the api you return Ok(dto) and when the user is calling Ok(dtoWithPassword).

And make sure that the password is hashed and salted.

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

2 Comments

But imagine I have another view where I only need to see the user Uername and PersonalInformation and both admin and user may ask for it.
You have to do authorization. For example basic auth is the simple. The user or admin sends his username and password with the request. And then you can have have a custom authorize attribute that sets the thread.currentprincipal to the user. Then in the method you can check if the user is an admin or a normal user. There are alot of videos on youtube to learn this.

Your Answer

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