Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

asp.net mvc - Redirect / show view after generated file is dowloaded

I've got a controller action that downloads a dynamically generated file:

    public ActionResult DownloadFile()
    {
        var obj = new MyClass { MyString = "Hello", MyBool = true };
        var ser = new XmlSerializer(typeof(MyClass));
        var stream = new MemoryStream();
        ser.Serialize(stream, obj);
        stream.Position = 0;

        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=myfile.xml");
        Response.ContentType = "application/xml";

        // Write all my data
        stream.WriteTo(Response.OutputStream);
        Response.End();

        return Content("Downloaded");
    }

Just for reference:

    public class MyClass
    {
        public string MyString { get; set; }
        public int MyInt { get; set; }
    }

This is working, and the file (myfile.xml) is downloaded.
However, the message "Downloaded" is not sent to the browser.

Similarly, if I replace return Content("Downloaded");
for return Redirect("www.something.com");
then the browser is redirected before the file downloads.

As a bit of a pre-amble, the user journey is:

  • User fills out form on previous view
  • Form is submitted
  • XML is generated and downloaded
  • User is redirected / "Downloaded" view is shown (so hitting F5 won't re-post the form)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Ross has said, you can only return one response to a HTTP request. What i do in that case is:

  1. Send the request to the server
  2. The server generates the file and stores it in some server side data structure (Cache, Usersession, TempData)
  3. The server returns a RedirectToAction() (POST, REDIRECT, GET pattern)
  4. The redirected action returns a View with some javascript which
  5. Triggers the download of the pregenerated file by setting window.location.href property to an special download action which sends the file back to the browser

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...