Asp.net ashx handler requests download instead of displaying file

I implemented a generic handler in my application, which is great for images, but when I manually type in the handler URL in the browser using the search button, it asks for loading instead of displaying. Here is my code:

public void ProcessRequest(HttpContext context)
        {
            if (this.FileName != null)
            {
                string path = Path.Combine(ConfigurationManager.UploadsDirectory, this.FileName);

                if (File.Exists(path) == true)
                {
                    FileStream file = new FileStream(path, FileMode.Open);
                    byte[] buffer = new byte[(int)file.Length];
                    file.Read(buffer, 0, (int)file.Length);
                    file.Close();
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileName + "\"");
                    context.Response.BinaryWrite(buffer);
                    context.Response.End();
                }
            }
        }

I use an octet stream because I am not only dealing with images, but I don’t always know the type of file content. Thanks in advance!

+3
source share
3 answers

ContentType, , , (, pdf ) (, MS Office )

, :

if(Path.GetExtension(path) == ".jpg")
   context.Response.ContentType = "image/jpeg";
else
   context.Response.ContentType = "application/octet-stream";
+6

ContentType , , .

theFile = GetFile(id)
context.Response.ContentType = theFile.Type;
+1

- , . , .

-1

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


All Articles