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

后端 未结 9 526
灰色年华
灰色年华 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:35

    If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...

    In my action method (which returns async Task<JsonResult>) I add the line (anywhere before the return statement):

    Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");
    
    0 讨论(0)
  • 2020-12-02 06:37

    I think that this might be helpful to you.

    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
    
    0 讨论(0)
  • 2020-12-02 06:44

    Note: The last line is mandatory.

    If we didn't specify Access-Control-Expose-Headers, we will not get File Name in UI.

    FileInfo file = new FileInfo(FILEPATH);
    
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = file.Name
    };
    response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
    
    0 讨论(0)
  • 2020-12-02 06:45

    You need to set the Content-Disposition header on the HttpResponseMessage:

    HttpResponseMessage response = new HttpResponseMessage();
    response.StatusCode = HttpStatusCode.OK;
    response.Content = new StreamContent(result);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "foo.txt"
    };
    
    0 讨论(0)
  • 2020-12-02 06:47

    This should do:

    Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题