2017-02-27 27 views
0

在我的asp.net webapi項目中,我需要返回字符串json數據作爲文件。還有一點很重要,我希望將響應的狀態碼設置爲200(成功)。我發現很多例子,人們使用MemoryStream和FileStreamResult從服務器獲取正確的文件,但它不適用於我。ASP.NET Core WebApi - 下載文件導致錯誤信息

不幸的是,我總是在瀏覽器中看到「意外錯誤」的消息,儘管serwer代碼沒有任何例外。我在瀏覽器中查看了請求的詳細信息,並且其狀態碼爲「錯誤請求」(400)。

我的代碼:

[HttpGet()] 
public async Task<IActionResult> Download() 
{ 
    string jsonData = "example data"; 
    byte[] byteArray = Encoding.UTF8.GetBytes(jsonData); 
    var stream = new MemoryStream(byteArray); 

    var result = new FileStreamResult(stream, new MediaTypeHeaderValue("text/json")) 
         { 
          FileDownloadName = "testFile.json" 
         }; 
    return result; 
} 
+0

它似乎有點像你正在尋找[東西在這個問題回答(http://stackoverflow.com/questions/41383338/how-to -download-A-zip文件-從-A-DOTNET-芯的WebAPI/41395761#41395761)。你嘗試過'返回Created(result);'? –

+0

它不適用於我:(。現在我得到消息:ERR_INVALID_RESPONSE。請使用您的示例作爲基於字符串變量的流,而不是從服務器上的實際現有文件中獲取它。 – Ellbar

回答

0
[HttpGet()] 
    public async Task<HttpResponseMessage> Download() 
    { 
     string jsonData = "example data"; 
     byte[] byteArray = Encoding.UTF8.GetBytes(jsonData); 

var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new ByteArrayContent(byteArray)}; 
      result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
      result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(Inline) { FileName = "testFile.json" }; 
      return result; 

    } 
+0

我無法編譯您的解決方案,因爲2錯誤: (1):'FileStreamResult'不包含'Content'的定義,並且沒有擴展方法'Content'接受類型爲'FileStreamResult'的第一個參數可能被發現 (2):無法隱含轉換類型System。 Net.Http.StringContent到System.Net.Http.HttpResponseMessage – Ellbar

+0

對不起,試試這個 – agfc

+0

現在代碼已經編譯完成,但是結果在瀏覽器中以json的形式返回,而不是作爲下載的文件返回。 – Ellbar