In my Blazor app I have a scoped service:
DownloadingFile.cs
namespace MyNamespace {
public class DownloadingFile
{
public byte[] theFile { get; set; }
}
}
I have it annotated in Startup.cs:
Startup.cs
services.AddScoped<DownloadingFile>();
I can successfully access it from a .RAZOR file:
MyFile.razor
<div @onclick="MyTask">Click Me</div>
@code {
[Inject]
private NavigationManager navigationManager { get; set; }
[Inject]
DownloadingFile downloadingFile { get; set; }
private async Task MyTask(){
APIResponse apiResponse = await APIResponse.getResponse();
downloadingFile = apiResponse.data;
navigationManager.NavigateTo("/api/Download/DownloadFile?filename=" + apiResponse.filename, true);
}
}
I have a download controller in:
MyNamespace
`- Controllers
`- DownloadController.cs
DownloadController.cs
namespace MyNamespace.Controllers {
[Route("api/[controller]")]
[ApiController]
public class DownloadController : ControllerBase
{
[HttpGet("[action]")]
public IActionResult DownloadFile(string filename)
{
byte[] theByteArray = new byte[] {1, 2, 3, 4, ... };
return File(theByteArray, "application/zip", filename);
}
}
}
If I run my Blazor app as is, everything works perfectly.
However, as you expect, I cannot hard-code in theByteArray
, it needs to be dynamic. If I change my download controller:
namespace MyNamespace.Controllers {
[Route("api/[controller]")]
[ApiController]
public class DownloadController : ControllerBase
{
// TO THIS
private DownloadingFile downloadingFile;
public DownloadController(DownloadingFile downloadingFile)
{
this.downloadingFile = downloadingFile;
}
// OR THIS
private DownloadingFile downloadingFile;
public DownloadController() {
downloadingFile = new DownloadingFile();
}
[HttpGet("[action]")]
public IActionResult DownloadFile(string filename)
{
return File(downloadingFile.theFile, "application/zip", filename);
}
}
}
The DownloadingFile
always comes up null
in the DownloadController.
EDIT: To clarify, the object I create from instantiating DownloadingFile in my controller is not null, it is the byte array I was expecting to be there that is null.
If I can just get the byte array from the .RAZOR file to the .CS file, everything will be fine. How do I go about doing this?