Api Clients

We recommend that you do all your database operations inside Api Controllers. The reason has been alluded to before. Namely, because of the nature of Blazor, it is sometimes not safe to access ApplicationDbContext directly from your Blazor pages or components. Therefore, it is better to encapsulate database operations in Api Controllers. The second benefit is that at some point in the future when you want to access your data from a mobile application, you already have the Apis to do it!

Take a look at our UsersController class. Then look for an interface named IUsersClient. Notice the same methods are defined on there. If you want to call an Api Controller method from your Blazor page or components, it's as easy as @inject IUsersClient UsersClient and using it. This is all accomplished using zero-configuration techniques and service discovery that we use all over the place. All you have to do is create your controller, create the client interface, and you're done.

Authorization

You may wonder how authorization works for all the http clients. If you look in the AuthorizationMessageHandler middleware, you will notice that it is setting the Cookie before each request if there is one. That cookie comes from _Host.cshtml by way of the HttpContext. Because Blazor is a vastly different model than traditional Asp.Net Core applications, it has certain constraints, one of them being that you can't access HttpContext from virtually anywhere except _Host.cshtml, which is actually just a regular Razor page. You then have to pass down context information to wherever you may need it. Here we leverage the ApplicationStateService to store the authorization cookie.

Table of Contents



An error has occurred. This application may no longer respond until reloaded. Reload 🗙