預期結果:用戶選擇通過可能需要很長時間的寧靜呼叫下載報告的選項後,會打開一個新選項卡,並顯示消息「請稍候「我想將控制權還給瀏覽器,以便用戶可以從」請稍等「瀏覽器選項卡重新點擊開窗器瀏覽器選項卡並繼續瀏覽網站。我放在一起的代碼會運行,但不會產生所需的結果,它的行爲方式與我的代碼的非異步版本相同 - 也就是說,用戶的開啓器選項卡保持綁定狀態,直到獲得下載的調用完成。我嘗試過其他模式,但所有結果都一樣 - 沒有我期望的異步行爲。我正在努力做什麼,如果是這樣,我不瞭解什麼?在C#中使用MVC 4中的RESTful HTTP請求異步等待
C#代碼:
public class ReportsController : Controller
{
public async Task GetDownloadAsync(string docId, string docName, string startDate, string endDate, string format)
{
//make request:
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create("http://myServerAddress");
GETRequest.Method = "GET";
GETRequest.ProtocolVersion = HttpVersion.Version11;
GETRequest.Accept = CreateHeader(format);
Task<WebResponse> getResponseTask = GETRequest.GetResponseAsync();
WebResponse GETResponse = await getResponseTask;
(HttpWebResponse)GETRequest.GetResponse();
Stream GETReponseStream = GETResponse.GetResponseStream();
//retrieve response into byteArray:
byte[] responseByteArray = convertStreamToByteArray(GETReponseStream);
string fileName = string.Format("{0}-{1}.{2}", docName, DateTime.Now.ToString("o"), CreateFileExt(format));
Response.ClearContent();
Response.ContentType = CreateHeader(format);
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
Response.AddHeader("Content-Length", GETResponse.ContentLength.ToString());
Response.BinaryWrite(responseByteArray);
}
}
我打電話從一些JavaScript的CSHTML鑑於這樣該控制器功能:
var win = window.open(encodeURI("GetDownloadAsync?docId=" + docId + "&docName=" + docName + "&startDate=" + startDate + "&endDate=" + endDate + "&format=" + reportType));