2012-08-12 47 views
2

我試圖讓用戶下載一個文件,並且已經嘗試了很長一段時間,但無濟於事得到這個工作。 我一直使用的代碼是:無法在ASP.NET MVC中添加標題到響應

A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll 
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll 
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll 
A first chance exception of type 'System.NullReferenceException' occurred in WebDev.WebHost40.dll 

(ETC)

更改我的調試設置:

Response.ClearHeaders(); 
Response.Clear(); 
Response.BufferOutput = true; 
Response.AddHeader("Content-disposition", 
        "attachment; filename= "+ Path.GetFileName(path) + fileType);      
Response.ContentType = "application/octet-stream"; 
Response.BinaryWrite(buffer); 
Response.Flush(); 
Response.Close(); 
Response.End(); 

不幸的是,當我試圖使它運行,除了大量的異常的什麼也沒有發生我發現我得到的例外是

「服務器無法設置內容t在發送HTTP標頭之後的ype。「

我已經通過Google搜索並嘗試了很多解決方案,但目前爲止沒有任何工作。據我所知,這是唯一一次使用響應 - 除非發生一些後臺進程(如果是這樣,我該如何改變它?)。請注意,我正在使用Asp.NET MVC。

任何想法?

編輯: 下面是一些情況下,這可能有助於解決這個問題:

的代碼是一個已經通過Ajax,原因是我需要調用通過在服務器端稱爲WEBMETHOD內客戶端(不好的做法,但它提供的時間需要),我也需要通過一個參數。

這裏是Ajax調用:

$("#Button").each(function() { 
       this.submitting = false; //To prevent double-clicking problems 
      }).on("click", function (e) { 
       if (e.preventDefault) e.preventDefault(); 
       $.ajaxSetup({ cache: false }); 
       e.preventDefault(); 
       if (!this.submitting) 
       { 
        this.submitting = true; 
        var self = this; 
        $.ajax({ 
         url: 'Controller/retrieveFile', 
         type: 'POST', 
         data: { SystemNumber: $("#Button").val() }, 
         dataType: 'json', 
         success: function (data) { 
          self.submitting = false; 
         }, 
         error: function() { 
          self.submitting = false; 
         } 
        }); 
       } 
      }); 

是這樣的,也許,有返回值的問題嗎?目前,我回到

Json(true, JsonRequestBehavior.AllowGet); 
+0

你能說明你的'Response'代碼適合整體流程嗎?如在哪個控制器方法?斷斷續續地診斷問題很困難。 – 2012-08-12 21:20:33

+0

我只是在想這個!給我一點時間:) – 2012-08-12 21:21:02

+0

問題已更新。 – 2012-08-12 21:26:42

回答

0

使用HttpContext.Response.AppendHeader( 「內容處置」,....)和擺脫Response.ClearHeaders()的嘗試;和Response.Clear();線。

此外,您應該考慮使用FileContentResult作爲您的方法的返回類型。

相關問題