Why two requests when I download a file?

I have an action which serves a file:

public override FileContentResult Foo() {
  var someDataAsBytes = ...
  return File(someDataAsBytes, "text/csv", "somefilename.csv");

The form is simple:

<form method="get" action="/Foo" id="myForm">
  <button type="submit">Download</button>

I initiate the download via script (so the page doesn’t change):

$("#myForm").on("submit", function() {
  window.location.href = $(this).attr("action");
  return false;

Problem is that two requests are sent to the server: one GET and one HEAD. And the action runs twice, but only serves the file once.

How do I get it to only send one request? Or is this normal behavior?

Extra info:
I inspected this in Fiddler, and the responses to the GET and POST are identical, except the GET has a non-zero Content-Length and the actual payload data. The response to the HEAD has nothing. Both return 200 OK status codes. Is this normal?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I do not see anything wrong with your code. I replicated your code and tried to reproduce the issue which you are facing. But I am not able to repro in Chrome, IE and Firefox.

It looks like this issue is specific to FireFox browser of yours and due to some plugin/Extension. Disable all the plugins in the browser and give it a try, it should work.

Solution 2

You are missing with e.preventDefault() in your script. What is happening here is your action is hit by both script and normal post. So if you put e.preventDefault() like below, then it will prevent browser’s default postback and only javascript’s code will execute your request.

$("#myForm").on("submit", function(e) {
  window.location.href = $(this).attr("action");

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply