【问题标题】:Download a file with ASP.NET Core Razor page使用 ASP.NET Core Razor 页面下载文件
【发布时间】:2020-07-16 21:14:49
【问题描述】:

澄清编辑我创建了一个新项目,试图将我原来的 MVC 项目转换为现在只使用 Razor 页面。我原来的解决方案是Here。

我花了一段时间才完成转换以显示文档列表,但我现在已经完成了。我一直在努力尝试下载该文件,但它一直告诉我该文件不存在,即使它已列出。

错误消息

No webpage was found for the web address: https://localhost:5001/FileShare/DownloadStub?id=SCHWADERER_PayStub_191018_1026.pdf

这是我的模型

文件数据模型.cs

    public class FileDataModel
    {
        public string FileName { get; set; }
        public string Size { get; set; }
        public string DateModified { get; set; }
        public string ParentDirName { get; set; }
        public string SubDirName { get; set; }  
    }

页面背后的代码

文件共享.cshtml.cs

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

            await file.DownloadToStreamAsync(memoryStream);
            Stream fileStream = file.OpenReadAsync().Result;
            return File(fileStream, file.Properties.ContentType, file.Name);
            
        }

最后是网页上的代码

文件共享.cshtml

table class="table table-bordered">
    <thead>
    <tr>
        <th>File Name</th>
        <th>File Size</th>
        <th>File Date</th>
        <th>Download</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var data in Model.FileDataModels)
    {
        <tr>
            <td>@data.FileName</td>
            <td>@data.Size</td>
            <td>@data.DateModified</td>
            <td><a class="btn btn-primary btn-sm"
                    href="/FileShare/DownloadStub?id=@data.FileName">Download</a></td>
        </tr>
    }
    </tbody>
</table>

我没有将正确的值传递给 href 吗?

我还需要捕捉其他价值吗?

是否应该使用 taghelper 来完成?

我不确定发生了什么以及我需要做什么才能朝着正确的方向前进。任何提示将不胜感激!

【问题讨论】:

  • 按照您提供的链接,我看到控制器名称是FileController,但您向我们展示的网址指向FileShare,这是视图的名称。你重命名了控制器吗?
  • 这是一个新项目。我将原始版本作为 MVC 构建,而这个是 Webapp 构建。我正在练习边做边学,并且只想将 MVC 项目转换为剃须刀页面。这可能会也可能不会起作用:/

标签: c# asp.net asp.net-core razor


【解决方案1】:

错误消息说它找不到您的网址,与文件无关。默认情况下,url 作为 Controller/Action/Parameter 而不是查询字符串,所以你的 URL 应该是 /FileShare/DownloadStub/@data.FileName

但我建议为此使用 RAZOR,因为如果您将来要自定义 URL 的创建方式(如下所示),它可以让您正常运行,即使不确定使用什么作为控制器名称(可能是文件共享):

@Html.ActionLink("Description", "DownloadStub", "FileShare", new { id = data.FileName}, null);

【讨论】:

  • 默认情况下,MVC 支持查询和休息格式,所以?id=value 也应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2019-06-25
  • 2018-04-05
  • 2018-12-20
  • 2020-08-14
  • 2020-08-22
  • 2019-03-09
  • 1970-01-01
  • 2021-07-04
相关资源
最近更新 更多