Changing the name in the header for a resource handler in C #

I have a resource handler which is Response.WriteFile (filename) based on the parameter passed through the request. I handle mimetype correctly, but the problem is in some browsers, the file name appears as Res.ashx (handler name) instead of MyPdf.pdf (the file I output). Can someone tell me how to change the file name when sending it 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);
+3
source share
3 answers

Expanding from Joel's comment, your actual code would look something like this:

context.Response.AddHeader("content-disposition", "attachment; filename=" + resource);
+4
source

This post by Scott Hanselman should be helpful:
http://www.hanselman.com/blog/CommentView.aspx?guid=360

+1
source

Thank you guys for your answer. The final code works and checks the PDF.

if (extensionArray[extensionArray.Length - 1].ToLower() == "pdf")
    context.Response.AddHeader("content-disposition", 
        "Attachment; filename=" + resource);
0
source

Source: https://habr.com/ru/post/1698934/


All Articles