Search code examples
c#asp.netasp.net-mvcasp.net-coreasp.net-core-mvc

How to create valid file name in http header from user input


ASP.NET 7 MVC application running in Debian with Apache should open PDF files in browser. Implamented solution from Make a file open in browser instead of downloading it

and

how to specify name for saving pdf from browser

Controller contains code

  public async Task<IActionResult> OpenPdf()
  {
    byte[] pdf = CreatePdf();
    string filename = "\",'õäöü";
    Response.Headers.Add("Content-Disposition", $"inline; filename={filename}.pdf");
    return File(result, "application/pdf");
    }

Issues:

  1. Chrome throws error ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION Accoding to Duplicate headers and Calling the file in the wrong path

This is caused by characters like

',"

in header.

  1. If those characters are removed, error illegar control character in header occurs only in Apache (running from Visual Studio IDE works OK). This is probably caused by õäöü characters.

How to encode file name in http header ?

According to Duplicate headers and Calling the file in the wrong path only alphanumeric characters are allowed. How to convert any unicode string to meaningful legal file name for header?

In this case üõöä should replaced to uooa characters, quotes, samces and comma can removed. However file name comes from user input and may contain any unicode characters.


Solution

  • You need to use UrlEncode for file names, Url names, etc.

    var encodedFileName = HttpUtility.UrlEncode(fileName + ".pdf",  System.Text.Encoding.UTF8)
    Response.Headers.Add("Content-Disposition", $"inline; filename={encodedFileName}");