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

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

    You need to add the content-disposition header to the response:

     response.StatusCode = HttpStatusCode.OK;
     response.Content = new StreamContent(result);
     response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
     return response;
    
    0 讨论(0)
  • 2020-12-02 06:51

    If you want to ensure that the file name is properly encoded but also avoid the WebApi HttpResponseMessage you can use the following:

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

    You may use either ContentDisposition or ContentDispositionHeaderValue. Calling ToString on an instance of either will do the encoding of file names for you.

    0 讨论(0)
  • 2020-12-02 07:02

    EDIT: As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;. You should use the accepted answer Darin made if your file name could contain a semi-colon.

    Add a Response.AddHeader to set the file name

    Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");
    

    Just change FILE_NAME to the name of the file.

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