I'm getting ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION when returning my docx file, however I'm not sure where in my header the error comes from. I've tried my best to remove anything that is dynamic and hardcoded to figure it out, to no avail.
byte[] byteArray = File.ReadAllBytes(#"T:\Praktik log\Learning Goals.docx");
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray,0,byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true))
{
RevisionAccepter.AcceptRevisions(wordDoc);
wordDoc.MainDocumentPart.Document.Body.InsertAt(
new Paragraph(
new Run(
new Text("Newly inserted paragraph."))), 0);
}
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", mem.ToArray().Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ActivationKey.docx\"; " +
"size=" + mem.ToArray().Length + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//Write it back to the client
Response.BinaryWrite(mem.ToArray());
Response.End();
I can download it on IE as it's gives crap about security, but chrome says nogo, and I need to have Chrome support for this download.
EDIT: Fiddler response: https://prnt.sc/pddibg
You're doing one weird thing.
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
ASP.NET places some headers itself.
Please try to not remove them and use native (if they exist for headers you're trying to modify, of course) ASP.NET methods to modify response headers.
Also you can setup a HTTP debugging proxy.
It will help you see what exactly you are doing wrong.
Here's some HTTP debugging proxies I know: Fiddler, Wireshark or Charles (paid, requires Java).
This guy achieved file downloading via returning System.IO.File.
Also this question looks like yours.
Check these answers, they may help you.
I achieved downloading a named file via:
[HttpGet]
public void Get()
{
Response.Headers.Add("Content-Disposition", "attachment; filename=\"file.bin\"");
var buffer = Enumerable.Repeat((byte) 0xF, 2048).ToArray(); //bytes
Response.Body.Write(buffer, 0, buffer.Length);
}
Tested on Google Chrome (Version 77.0.3865.90).
File downloaded and contains 2048 bytes of data.
Server response in Fiddler: screenshot
Related
I want to allow users to display a pdf and save it on my asp.net project.
My code is below:
string yol = e.CommandArgument.ToString();
string path = Server.MapPath("~/Raporlar/2021/" + yol.Trim());
WebClient User = new WebClient();
Byte[] s = User.DownloadData(path);
System.IO.MemoryStream ms = new System.IO.MemoryStream(s);
if (ms != null && ms.Length > 1)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Charset = "UTF-8";
Response.Buffer = true;
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=\"" + yol + "\"");
Response.AddHeader("Expires", "0");
Response.AddHeader("Pragma", "cache");
Response.AddHeader("Cache - Control", "private");
Response.ContentType = "application/pdf";
Response.BinaryWrite(ms.ToArray());
Response.Flush();
try { Response.End();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
catch { }
}
The display button only works Firefox. Other browsers (Google Chrome, Opera, Edge..) is not display the pdf and gives error like that:
Hmmm… This page is not available. The web page at https://massgrup.com/Raporlar.aspx may be experiencing some problems or has been permanently moved to a new web address.
ERR_HTTP2_PROTOCOL_ERROR
I solved the problem. It is about ssl certifica.
When i click the button the link is like this : "https:https://massgrup.com/"
Because of that the button is not working on Chrome browsers.
After removing the ssl certificate the problem is resolved.
But now I will have to solve the problem of how to install the ssl certificate. This is a different situation.
I am creating a zip by Ionic.Zip.dll like this (ASP.NET,C#):
zip.AddEntry("Document.jpeg", File.ReadAllBytes("Path");
I want to download it like this:
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=SuppliersDocuments.zip";
zip.Save(Response.OutputStream);
Response.Close();
I tested this code in localhost by Firefox and Chrome and it worked properly. But when I test this code in host, I get this error:
Failed - network error
Is my code is wrong?
I ran into a similar issue with relaying an SSRS report. Taking #Arvin's suggestion, I did the following:
private void CreateReport(string ReportFormat)
{
ReportViewer rview = new ReportViewer();
// (setup report viewer object)
// Run report
byte[] bytes = rview.ServerReport.Render(ReportFormat, deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);
// Manually create a response
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-disposition", string.Format("attachment; filename={0}.{1}", fileName, extension));
// Ensure the content size is set correctly
Response.AddHeader("Content-Length", bytes.Length.ToString()); // <- important
// Write to the response body
Response.OutputStream.Write(bytes, 0, bytes.Length);
// (cleanup streams)
}
The fix was adding the Content-Length header and setting it to the size of the byte array from reporting services.
Not sure if this is an actual problem or not, but I'm writing a file out in ASP.NET, and even though the file always successfully goes through, in Chrome's developer tools, network tab, I always see the line in red, marked "Canceled".
I've tried lots of ways of doing this - for simplicity, I'm trying this with a simple text file, but it's true for PDF and other file types as well.
WebForms: I've tried it with lots of combinations of the following:
Response.Clear();
// and/or/neither
Response.ClearHeaders();
// with and without this
Response.Buffer = true;
Response.Charset = "";
// or/neither
Response.Charset = "utf-8";
// application/pdf for PDF, also tried application/octet-stream
Response.ContentType = "text/plain";
// with and without this
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=1.txt");
// bytes is the UTF8 bytes for a string or the PDF contents
new MemoryStream(bytes).WriteTo(Response.OutputStream);
// or
Response.Write("12345");
// any combination of the following 3, or none at all
Response.Flush();
Response.Close();
Response.End();
MVC (2 and 3, haven't tried 4):
byte[] fileContents = Encoding.UTF8.GetBytes("12345");
return File(fileContents, "text/plain", "1.txt");
// or
return File(#"C:\temp\1.txt", "text/plain", "1.txt");
It's always the same - the file goes through just fine, but dev tools shows me this:
I'm thinking of just ignoring it and moving on with life, but the red just bothers me. Any idea how I can deal with that?
This just means that chrome didn't navigate away from the page. The behavior is by design. Don't worry about it.
So here is my problem: I have a code that use response to ExportFile, but the problem is after the response code. the succeeding code no longer executes or it is like being read but ignored. sorry for being noob. so here is my code:
fullFilePath = "" + rootPath + "" + Filename + ".xlsx";
string fileName = fullFilePath.Substring(fullFilePath.LastIndexOf('\\') + 1);
byte[] buffer;
using (FileStream fileStream = new FileStream(fullFilePath, FileMode.Open))
{
int fileSize = (int)fileStream.Length;
buffer = new byte[fileSize];
// Read file into buffer
fileStream.Read(buffer, 0, (int)fileSize);
}
Response.Clear();
Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.CacheControl = "public";
// writes buffer to OutputStream
Response.OutputStream.Write(buffer, 0, buffer.Length);
newFile.Delete();
ClientScript.RegisterStartupScript(GetType(), "id", "EnableCtrl()", true);
after this has been executed the javascript "EnableCtrl()" is not being fired or triggered. And when I delete the part of code which is related to response and change it to something else the javascript is being triggered. So how could i run a javascript after a response code?
The script won't/can't be triggered this method because the browser has already been sent the response: which is the file, and not the markup from a post-back. One request. One response. And it wasn't the post-back markup.
Instead, I would suggest either:
Handling the "Client Click" of the initiating control in the browser as well (the action could be delayed with setTimeout). Browser won't actually refresh the page/DOM because of the attachment disposition in the response, which is why this works. However, there are no client-side events for if a download was accepted, has started, or has completed1
Change the design so the "download" is a separate action with no other side-effect.
Happy coding.
1 It's possible to contrive server-assisted setups that allow the client to query the progress of a download, much like an upload progress indicator. However, this is not trivial or standard and may still not accurately reflect the state.
So, I user a bit of code to force a download on my ASP.Net based project. This bit of code works in Firefox and Chrome, bu not in IE for some strange reason. Even stranger, it worked in all three initially, and just stopped working in IE recently. Below is the code I used, please let me know if any adjustments need to be made or what the problem with with may be.
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "Application/pdf";
Response.AppendHeader("content-disposition","attachment; filename=" + path);
Response.WriteFile(path);
Response.End();
More details
Here is the revamped code, still doesnt work for IE.
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "Application/pdf";
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = type;
Response.AddHeader("content-disposition","attachment; filename=" + path);
Response.WriteFile(path);
Response.End();
You should probably try to set the mime type to "application/octet-stream". If you don't want a specific handler to respond to the mime-type.
Should this code
Response.AddHeader("content-disposition","attachment; filename=" + path);
be changed as
Response.AddHeader("content-disposition","attachment; filename=" + name + "." + ext);
or
Response.AddHeader("content-disposition","attachment; filename=" + name + ".pdf");
Other things to check for
Response.Buffer to true in the beginning
Response.clear in the beginning
Use response.binarywrite instead of writefile
Response flush at the end
Ensure no HTML or space characters written to the response.stream other than the binarywrite.
Problem solved. The reason it was not going through was due to an extra form that was present on the master page, apparently overlaying the buttons. Once that was fixed, It worked properly in all browsers.
Adding the following two lines at the top, fixed it for me:
Response.ClearContent();
Response.ClearHeaders();