Search code examples
asp.net-corerazorazure-storageazure-storage-files

Azure File Share - File not found (404) even though it lists the files in my application


Maybe i'm calling the wrong Task action on the method since it works on an MVC project just fine. This is strictly trying to play with it on a Razor Page, not MVC.

When I call OnGetAsync() my page does indeed populate all of the files available. However, when I try to download the file, it shows file not found.

DownloadStub method:

public async Task<IActionResult> DownloadStub(string id)
        {
            string fileStorageConnection = _configuration.GetValue<string>("fileStorageConnection");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(fileStorageConnection);
            CloudFileShare share = storageAccount.CreateCloudFileClient().GetShareReference("test");
            CloudFileDirectory rootDir = share.GetRootDirectoryReference();
            CloudFileDirectory dir = rootDir.GetDirectoryReference(@"E000002/stubs");
            CloudFile file = dir.GetFileReference(id);

            if (!file.Exists())
            {
                ModelState.AddModelError(string.Empty, "File not found.");
                return Page();
            }
            else
            {
                await file.DownloadToStreamAsync(new MemoryStream());
                Stream fileStream = await file.OpenReadAsync();
                return File(fileStream, file.Properties.ContentType, file.Name);
            }

        }

cshtml page

<td>
    <a class="btn btn-primary" href="~/Files/[email protected]">Download</a>
</td>

When I try setting a breakpoint on the method, it does not get hit, which I think is part of the issue but I don't know how to investigate it further.

To see my other implementations for this page you can review this post if it helps.

View of files being returned. Folders


Solution

  • For razor pages,the page method name in razor pages is different from action method in mvc.It would be like:OnGetMethodName for get method and OnPostMethodName for post method.

    Reference:

    https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio#multiple-handlers-per-page

    Change your razor pages like below:

    <td>
        <a class="btn btn-primary" href="~/[email protected]&handler=DownloadStub">Download</a>
    </td>
    

    Backend code:

    public class IndexModel : PageModel
    {
        public void OnGet()
        {
           //...
        }
        public void OnGetDownloadStub(string id)
        {
           //do your stuff...
        }
    }
    

    Result: enter image description here