以下のコードは、あなたが尋ねたことを正確に行っています。
それは、追加のHTMLタグをレンダリングするので、メッセージがユーザーに表示された後、ダウンロードが開始:HTTPヘッダが送信された後にサーバーがヘッダを付加することはできません。この例外が発生します
protected void Page_Load(object sender, EventArgs e)
{
var currentUrl = Request.Url.OriginalString;
var currentQuery = Request.Url.Query;
var download = new
{
FilePath = "~/test.csv",
FileName = "test.csv",
FileMime = "text/csv",
Message = "Excel generated!",
QueryParam = "direct-download",
Delay = 2 // seconds
};
var hasQueryParams = currentQuery.Length > 0;
var isDownloadUrl = hasQueryParams && currentQuery.IndexOf(download.QueryParam) >= 0;
if(isDownloadUrl)
{
// Prepare..
Response.ContentType = download.FileMime;
Response.Clear();
Response.BufferOutput = true;
// Transfer..
Response.AddHeader("content-disposition", "attachment; filename=" + download.FileName);
Response.WriteFile(download.FilePath);
// Done..
// Instead of Response.Close()
// http://stackoverflow.com/q/4583201/2361743
Response.Flush();
Context.ApplicationInstance.CompleteRequest();
return;
}
// Meta-Refresh Tag has to be in <HEAD> section, but not all browsers follow this restriction.
// IFRAME has to work fine. It is wrapped into <DIV> to be not visible in old browsers.
const string tagToStartManual = "<A href='{0}'>{1}</A>";
const string tagToStartAfterDelay = "<META HTTP-EQUIV='REFRESH' CONTENT='{1};URL={0}'>";
const string tagToStartImmediately = "<DIV STYLE='{1}'><IFRAME SRC='{0}'></IFRAME></DIV>";
const string cssToHideFrame = "width:1px;height:1px;opacity:0.1;overflow:hidden";
// Show your message..
// And add HTML Tags which would start download:
Response.Write(download.Message);
var downloadUrl = currentUrl + (hasQueryParams ? "&" : "?") + download.QueryParam;
// You don't have to use all 3 methods...
Response.Write(String.Format(tagToStartManual, downloadUrl, download.FileName));
Response.Write(String.Format(tagToStartAfterDelay, downloadUrl, download.Delay));
Response.Write(String.Format(tagToStartImmediately, downloadUrl, cssToHideFrame));
// Done.
// Waiting for actual download request...
}
。 – Petras