【问题标题】:MVC6 Web Api - Return Plain TextMVC6 Web Api - 返回纯文本
【发布时间】:2016-06-15 11:10:41
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    试试这个:

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

    【讨论】:

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

      【讨论】:

        猜你喜欢
        • 2014-08-10
        • 1970-01-01
        • 2012-07-19
        • 1970-01-01
        • 2019-08-03
        • 2020-06-05
        • 1970-01-01
        • 2016-07-19
        • 1970-01-01
        相关资源
        最近更新 更多