Search code examples
c#asp.net-corecontroller.net-8.0blazor-webapp

General Question on Navigation Manger vs HttpContext to route to a controller


In a Blazor web app on .NET 8, I am using a service to create a zip file, then calling a controller to return the zip to the user.

I ran into issues using HTTP context and was able to achieve what I wanted by injecting Navigation manager and navigating to my route.

So when using a controller I have two options of

NavigateTo("controller/Route")  

or

HttpContext.GetAsync("controller/route")
private async Task DownloadFiles()
{
    NavigationManager.NavigateTo("api/Download/download/test", true);
}

vs

private async Task DownloadFiles()
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync($"/api/download/download.test");
}

When to use which - and why?

And a bonus question what method makes the most sense for passing in parameters like

private async Task DownloadFiles()
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync($"/api/download?pathsInSharedDrive={string.Join(",", GetAllMarkedDownloadPaths())}");
}

Solution

  • With NavigationManager service you can implement Navigation guards in Blazor. It can ensure that users can only access authorized routes, improving both security and user experience. Also it is simpler to implement file download. However it is limited to handle the response, which means it will be difficult to implement your custom handling logic.

    While using httpClient.GetAsync you can deal with the response more freely and deal the data before saving. What is difficult is that you need more configuration for saving the file. Also the header the token need carefully configuring to ensure the security.

    As to passing parameters via query strings, I've met no apparent advantages and disadvantages of these methods, as it is rather a direct way.