问题
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>
</form>
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?
回答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.
回答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) {
e.preventDefault();
window.location.href = $(this).attr("action");
});
来源:https://stackoverflow.com/questions/30589864/why-two-requests-when-i-download-a-file