How to set downloading file name in ASP.NET Web API

后端 未结 9 631
灰色年华
灰色年华 2020-12-02 06:11

In my ApiController class, I have following method to download a file created by server.

public HttpResponseMessage Get(int id)
{
    try
    {
        strin         


        
9条回答
  •  没有蜡笔的小新
    2020-12-02 06:47

    Considering the previous answers, it is necessary to be careful with globalized characters.

    Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"

    Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]

    HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]

    UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]

    Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.

    Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");
    

    or with class aid:

    var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
    Response.AddHeader("Content-Disposition", cd.ToString());
    

    The System.Net.Mime.ContentDisposition class takes care of quotes.

提交回复
热议问题