【问题标题】:Create a downloadable file in C# (Umbraco)在 C# (Umbraco) 中创建一个可下载的文件
【发布时间】:2017-10-03 08:58:23
【问题描述】:

对于最近的一个项目,我们正在尝试在 C# Umbraco 中创建一个可下载的文件,但我似乎无法让它工作。对于下载,我使用 System.Web.HttpContext.Current.Response。在 Umbraco CMS 中按下按钮后调用该函数。该函数被调用,但没有响应下载。该函数在继承自 System.Web.Http.ApiController 的类中实现。

我知道这个问题与其他一些问题相匹配,但我尝试了不同的解决方案,我觉得我忽略了一些东西。

源代码:

[Route("feedback")]
[HttpPost]
public void Add(FeedbackRequest feedback)
{
    var Response = HttpContext.Current.Response;

    string filePath = "C:\\testfile.txt";
    var file = new FileInfo(filePath);

    if (file.Exists)
    {
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());

        //Doesn't work with plain/text either
        Response.ContentType = "application/force-download";
        Response.Flush();
        Response.TransmitFile(file.FullName);
        try
        {
            Response.End();
        }
        catch (ThreadAbortException err)
        {

        }
        catch (Exception err)
        {
        }
    }

}

【问题讨论】:

  • 您似乎在使用 ASP.NET MVC:从您的操作中返回 FilePathResult 有什么问题?
  • 我没有使用 MvcController,所以我不能使用像 filepathresult 这样的方法。我的控制器是 ApiController。

标签: c# asp.net-web-api download httpcontext


【解决方案1】:

问题是我的 js。我有:

            $http.get('/someurl/Export').             
             success(function (data) { 
                //console.log(data); 
                $scope.importOutput = data; 
        });

解决方法是:

window.open('/someurl/Export', '_blank'); 

感谢您的所有回答。我认为 js 很好,因为它正在处理调用,但它似乎不是。

【讨论】:

    【解决方案2】:

    你的方法设置为 void,它应该返回一个结果

    public ActionResult Add(FeedbackRequest feedback)
    {   
        string filepath = "some filepath";
        byte[] filedata = File.ReadAllBytes(filepath);
        string contentType = MimeMapping.GetMimeMapping(filepath);
    
        var contentInfo = new System.Net.Mime.ContentDisposition
        {
            FileName = "download filename",
            Inline = false,//ask browser for download prompt
        };
    
        Response.AppendHeader("Content-Disposition", contentInfo.ToString());
    
        return File(filedata, contentType);
    }
    

    【讨论】:

    • 当我尝试返回时得到以下信息:不可调用成员“文件”不能像方法一样使用。
    • 我尝试让我的控制器从 MvcController 继承以允许使用 File 作为方法,但是现在它无法找到我的路径。我会进一步研究它。
    猜你喜欢
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2018-02-09
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多