Skip to content

Instantly share code, notes, and snippets.

@AlexMAS
Created March 12, 2016 12:51
Show Gist options
  • Save AlexMAS/c874bc03bff8a2717e18 to your computer and use it in GitHub Desktop.
Save AlexMAS/c874bc03bff8a2717e18 to your computer and use it in GitHub Desktop.
Set Content-Disposition with encoded filename
public static void SetContentDispositionInline(this HttpResponse response, string fileName, string userAgent)
{
SetContentDisposition(response, "inline", fileName, userAgent);
}
public static void SetContentDispositionAttachment(this HttpResponse response, string fileName, string userAgent)
{
SetContentDisposition(response, "attachment", fileName, userAgent);
}
private static void SetContentDisposition(this HttpResponse response, string dispositionType, string fileName, string userAgent)
{
response.AddHeader("Content-Disposition", $"{dispositionType}; filename=\"{EncodeContentDespositionFileName(fileName, userAgent)}\"");
}
private static string EncodeContentDespositionFileName(string fileName, string userAgent)
{
if (!string.IsNullOrEmpty(fileName))
{
var fileNameEcoding = Encoding.UTF8;
// Microsoft Internet Explorer or Edge
if (!string.IsNullOrEmpty(userAgent)
&& ((userAgent.IndexOf("Edge", StringComparison.OrdinalIgnoreCase) >= 0)
|| (userAgent.IndexOf("MSIE", StringComparison.OrdinalIgnoreCase) >= 0)
|| (userAgent.IndexOf("Trident", StringComparison.OrdinalIgnoreCase) >= 0)
|| (userAgent.IndexOf("rv:11.0", StringComparison.OrdinalIgnoreCase) >= 0)))
{
fileNameEcoding = Encoding.GetEncoding("windows-1251");
}
var fileNameBytes = fileNameEcoding.GetBytes(fileName);
var dispositionFileName = "";
foreach (var b in fileNameBytes)
{
dispositionFileName += (char)(b & 0xff);
}
return dispositionFileName;
}
return fileName;
}
@AlexMAS
Copy link
Author

AlexMAS commented Mar 12, 2016

Example:

response.SetContentDispositionAttachment("Файл.pdf", requestUserAgent);

where requestUserAgent you can take from the request header.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment