Hi Folks! In this post I will show you how to track your page visits in Blazor with all the request information possible, but the challenge is that we don't have a standard request-response situation going on with Blazor Server Apps, it's a websocket connection that do all the interaction. So the answer may surprise you: we then use javascript! 😂
It's actually kinda obvious, if we don't have access to request information from a server perspective, we try a different approach from the client side. Remember: we cannot use the HttpContext object in Blazor components.
The easiest way to understand how everything works is to download the repository source-code: clone https://github.com/guilhermesuzuki/keep-track-of-your-page-visits-in-blazor-server.git
Browse to Index.razor in the solution and go to the end: you will notice a javascript call to websites.pages.view function. It uses a dependency injection to the JS runtime for blazor applications. And the call needs to happen in the OnAfterRender{Async} method, because that's how the JS runtime works.
Now go to a file called common.js in the wwwroot directory. If you open it, you will see the javascript function Index.razor calls. It basically gathers some information from the DOM context of the application (that's the secret to make tracking work) and then triggers the Views controller, Index method. The controller then register the visit in the SQLite database.
And that would be it! Feel free to ask any questions you might have in the comment section below, I will do my best to answer them.
Hope you guys enjoyed it. See ya!
I liked this article very much.