如何在ASP.NET Web API中设置下载文件名

Tae*_*hin 136 c# asp.net-web-api

在我的ApiController类中,我有以下方法来下载服务器创建的文件.

public HttpResponseMessage Get(int id)
{
    try
    {
        string dir = HttpContext.Current.Server.MapPath("~"); //location of the template file
        Stream file = new MemoryStream();
        Stream result = _service.GetMyForm(id, dir, file);
        if (result == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        result.Position = 0;
        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.OK;
        response.Content = new StreamContent(result);
        return response;
    }
    catch (IOException)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}
Run Code Online (Sandbox Code Playgroud)

除了默认下载文件名是其id之外,一切都工作正常,因此用户可能每次都需要在另存为对话框时键入他/她自己的文件名.有没有办法在上面的代码中设置默认文件名?

Dar*_*rov 280

您需要在以下位置设置Content-Disposition标题HttpResponseMessage:

HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "foo.txt"
};
Run Code Online (Sandbox Code Playgroud)

  • 对于任何对"附件"处置类型感兴趣的人,处理类型的完整列表位于http://www.iana.org/assignments/cont-disp/cont-disp.xhtml (20认同)
  • @Luminous"它是否重要"和"一个比另一个更流行,更优先吗?" 不,不.一个用于MVC`ActionResult`s,一个用于WebApi`HttpResponseMessage`s. (4认同)

Kin*_*ake 26

编辑:正如评论中所提到的,我的答案没有考虑需要像a一样转义的字符;.如果您的文件名可能包含分号,则应使用Darin所接受的答案.

添加Response.AddHeader以设置文件名

Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");
Run Code Online (Sandbox Code Playgroud)

只需将FILE_NAME更改为文件名即可.

  • 事实证明这有助于我解决问题提问者的类似问题.在我的情况下,我还发现将"附件"更改为"内联"非常有用,这样IE8就可以让我选择始终打开有问题的文件类型. (2认同)
  • 不包括逃避.如果文件名包含`;`或具有特殊含义的其他内容,该怎么办? (2认同)

sor*_*nhk 8

如果要确保文件名已正确编码,但也避免使用WebApi HttpResponseMessage,则可以使用以下命令:

Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());
Run Code Online (Sandbox Code Playgroud)

您可以使用ContentDisposition或ContentDispositionHeaderValue.在任一实例上调用ToString将为您执行文件名编码.


Jar*_*rek 6

我认为这可能对你有所帮助.

Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
Run Code Online (Sandbox Code Playgroud)

  • 不包括逃避.如果文件名包含`;`或具有特殊含义的其他内容,该怎么办? (3认同)