Created
March 12, 2016 12:51
-
-
Save AlexMAS/c874bc03bff8a2717e18 to your computer and use it in GitHub Desktop.
Set Content-Disposition with encoded filename
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
where
requestUserAgent
you can take from the request header.