MVC6 Web Api - 返回纯文本

时间:2016-03-02 14:26:24

标签: asp.net-web-api asp.net-web-api2 asp.net-core-mvc

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

我需要在我的一个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输出字符串?

2 个答案:

答案 0 :(得分:3)

顺便说一下:

<?php
$lastname  = "O'Reilly";
echo $lastname;
$_lastname = mysql_real_escape_string($lastname);
echo $_lastname ;
?>

答案 1 :(得分:2)

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