Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

HTTP API requests within context of an 'User' or 'Organisation' best practice

$
0
0

My ASP.NET Core project responds to incoming web requests from a user.

I'm wondering what is considered best practice if (for example) the user wanted to find out some information about themselves (such as what Organisation they belonged to).

Example classes:

public class User
{
     public string Name { get; set; }
     public Organisation Organisation { get; set;}
}

public class Organisation
{
     public string Name { get; set; }
     public IEnumerable<User> Users { get; set; }
}

Using the example above, the user's mobile device would send a GET request to:

/api/v1.0/User

My API uses the Unit of Work design pattern, which is hooked up via Dependency Injection in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
...
     services.AddScoped<IUnitOfWork, UnitOfWork>();
...
}


And Injected into my API Controllers:

// /api/v1.0/User
public UserController : Controller
{
    private readonly IUnitOfWork _uow;

    public UserController(IUnitOfWork uow) {
        _uow = uow;
     }

    public IActionResult GetUserInformation(string userName) {
     // Example code, for demo purposes.
     // This could return the User's Name and Organisation.
         return _uow.UserRepository.GetOne(userName);
     }
}

So this works fine for when the user wants their own data, but what about when the user wants to (say) return a list of other users who are in the same Organisation?


// /api/v1.0/Organisation
public OrganisationController : Controller
{
public IActionResult GetOrganisationUsers(string organisationName)
{
// The user would have to ask for the UserInformation in the previous code block, and then send another request to the OrganisationController to find what other Users are related to the same organisation.
return _uow.OrganisationRepository.GetOne(organisationName).Users;
}
}

My actual question is: Is this how I should be designing my API (each endpoint expecting an identifier of sorts), or is there a way I can simply 'inject' the context of an incoming client request? (for example, look up the bearer token to find a user from the database, and inject a "IUser" object into all of my controllers so that all further UnitOfWork calls are within context of the user).

I'm considering cases where the client is asking to return all users for an organisation, etc. Would I have to use EF Navigation Properties to do that? I'd imagine that would generate a lot of overhead for the server. (as opposed to having to perform repository/database lookups each time).

Thanks in advance.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>