While my server-side Blazor app is running, I want some Javascript code in _Host.cshtml
to be able to post data to a controller action. Of course, this happens comp
Use: endpoints.MapControllers()
You can have this in your startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
This controller:
[Route("api/[controller]")]
[ApiController]
public class DownloadController : Controller
{
private readonly IWebHostEnvironment environment;
public DownloadController(IWebHostEnvironment environment)
{
this.environment = environment;
}
[HttpGet("[action]")]
public IActionResult DownloadFile(string FileName)
{
string path = Path.Combine(
environment.WebRootPath,
"files",
FileName);
var stream = new FileStream(path, FileMode.Open);
var result = new FileStreamResult(stream, "text/plain");
result.FileDownloadName = FileName;
return result;
}
}
And this in your .razor page:
@inject NavigationManager NavigationManager
@code {
public void DownloadFile()
{
NavigationManager.NavigateTo($"/api/Download/DownloadFile?FileName=BlazorHelpWebsite.zip", true);
}
}
See: https://github.com/ADefWebserver/Blazor-Blogs/tree/master/BlazorBlogs