MVC6 Web Api - Return 纯文本

MVC6 Web Api - Return Plain Text

我在 SO 上查看了其他类似问题(例如这个 Is there a way to force ASP.NET Web API to return plain text?),但它们似乎都针对 WebAPI 1 或 2,而不是您使用 MVC6 的最新版本。

我需要在我的一个 Web API 控制器上 return 纯文本。只有一个 - 其他人应该保持 returning 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 输出字符串吗?

试一试:

var httpResponseMessage = new HttpResponseMessage();

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

return httpResponseMessage;

解决方案是 return 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");
}