2016-03-02 54 views
1

我已經看過其他類似的問題(例如這個Is there a way to force ASP.NET Web API to return plain text?),但它們似乎都是針對WebAPI 1或2,而不是您使用MVC6的最新版本。MVC6 Web Api - Return Plain Text

我需要在我的一個Web API控制器上返回純文本。只有一個 - 其他人應該繼續返回JSON。該控制器用於開發目的,用於輸出數據庫中的記錄列表,並將其導入到流量負載生成器中。這個工具需要CSV作爲輸入,所以我試圖輸出(用戶將只需要保存頁面的內容)。

[HttpGet] 
public HttpResponseMessage AllProductsCsv() 
{ 
    IList<Product> products = productService.GetAllProducts(); 
    var sb = new StringBuilder(); 
    sb.Append("Id,PartNumber"); 

    foreach(var product in products) 
    { 
     sb.AppendFormat("{0},{1}", product.Id, product.PartNumber); 
    } 

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); 
    result.Content = new StringContent(sb.ToString(), System.Text.Encoding.UTF8, "text/plain"); 
    return result; 
} 

基於各種搜索,這似乎是最簡單的方法,因爲我只需要這一個操作。然而,當我要求這個,我得到下面的輸出:

{ 
   "Version": { 
      "Major": 1, 
      "Minor": 1, 
      "Build": -1, 
      "Revision": -1, 
      "MajorRevision": -1, 
      "MinorRevision": -1 
   }, 
   "Content": { 
      "Headers": [ 
         { 
            "Key": "Content-Type", 
            "Value": [ 
               "text/plain; charset=utf-8" 
            ] 
         } 
      ] 
   }, 
   "StatusCode": 200, 
   "ReasonPhrase": "OK", 
   "Headers": [], 
   "RequestMessage": null, 
   "IsSuccessStatusCode": true 
} 

如此看來,MVC仍試圖輸出JSON,我不知道爲什麼他們倒是輸出這些值。當我一步一步調試代碼時,我可以看到StringBuilder的內容沒問題,我想輸出什麼內容。

有什麼簡單的方法來輸出一個字符串與MVC6?

回答

1

的解決方案是返回一個FileContentResult。這似乎繞過了內置格式化程序:

[HttpGet] 
public FileContentResult AllProductsCsv() 
{ 
    IList<Product> products = productService.GetAllProducts(); 
    var sb = new StringBuilder(); 

    sb.Append("Id,PartNumber\n"); 

    foreach(var product in products) 
    { 
     sb.AppendFormat("{0},{1}\n", product.Id, product.PartNumber); 
    } 
    return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/csv"); 
} 
2

一展本:

var httpResponseMessage = new HttpResponseMessage(); 

httpResponseMessage.Content = new StringContent(stringBuilder.ToString()); 
     httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); 

return httpResponseMessage; 
相關問題