Changing the name in the header for a resource handler in C#
-
05-07-2019 - |
Question
I have a resource handler that is Response.WriteFile(fileName) based on a parameter passed through the querystring. I am handling the mimetype correctly, but the issue is in some browsers, the filename comes up as Res.ashx (The name of the handler) instead of MyPdf.pdf (the file I am outputting). Can someone inform me how to change the name of the file when it is sent back to the server? Here is my code:
// Get the name of the application
string application = context.Request.QueryString["a"];
string resource = context.Request.QueryString["r"];
// Parse the file extension
string[] extensionArray = resource.Split(".".ToCharArray());
// Set the content type
if (extensionArray.Length > 0)
context.Response.ContentType = MimeHandler.GetContentType(
extensionArray[extensionArray.Length - 1].ToLower());
// clean the information
application = (string.IsNullOrEmpty(application)) ?
"../App_Data/" : application.Replace("..", "");
// clean the resource
resource = (string.IsNullOrEmpty(resource)) ?
"" : resource.Replace("..", "");
string url = "./App_Data/" + application + "/" + resource;
context.Response.WriteFile(url);
Solution
Extending from Joel's comment, your actual code would look something like this:
context.Response.AddHeader("content-disposition", "attachment; filename=" + resource);
OTHER TIPS
This Scott Hanselman post should be helpful:
http://www.hanselman.com/blog/CommentView.aspx?guid=360
Thank you guys for your answer. The final code works and checks for pdf.
if (extensionArray[extensionArray.Length - 1].ToLower() == "pdf")
context.Response.AddHeader("content-disposition",
"Attachment; filename=" + resource);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow