Search code examples
blazorblazor-server-sideblazor-client-side

Can a single Blazor project contains both WebAssembly part and server-side part?


Now that Blazor WebAssembly is officially released, I gave it a try by creating my first Blazor wasm project using the template, but quickly noticed that one thing is pretty different what I would expect. It appears that there is no "server" part in the template, and the published result consists only of static assets (including all the .dll files). Naturally, I then wonder how may I access my online database? Allowing client-side to have direct access to my database sounds like a terrible idea (if it can be done at all), since I will have to include my connection string somewhere in my client-side code... definitely NO!

And after a quick search on Google, it seems that everyone is using another server to serve the data using API. OK, fine, but wouldn't it be much better if I can include my server part in the same project, and communicate with my client-side also using WebSocket (just like in Blazor server) rather than API? Is that possible?


Solution

  • You can create a WebAseembly Blazor hosted App. If you're using Visual Studio to create your project, you should check out the Hosted checkbox. This create for you 3 projects. One for the WebAseembly Blazor App (Client folder), the second for hosting and serving (Server folder) the client-side Blazor app, and the third ( Shared folder) is for shared object between the two projects, as for instance, database models.

    The Server app also contains controller class, which is used to demonstrate how to call a Web Api endpoint from the client Blazor to the Server (Web Api). You may create a dedicated Web Api for enabling access to your database data instead.

    Note: As the Blazor client side app runs on the browser, you cannot access your database directly. You should use HTTP calls to your Web Api endpoints, the actions of which methods may retrieve the data directly from the database (not recommended), or indirectly by creating database access services or repositories.

    Update:

    The Main means of transportation between the client-side and the server-side( or to be more precise web api endpoints) is the Fetch Api; that is, you need to perform HTTP calls to your Web Api. However, you may use SignalR in your client app (Client SignalR). See sample here: