gpt4 book ai didi

asp.net-web-api - MVC6 Web Api - 返回纯文本

转载 作者:行者123 更新时间:2023-12-01 00:31:35 25 4
gpt4 key购买 nike

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

我需要在我的 Web API Controller 之一上返回纯文本。只有一个 - 其他应该继续返回 JSON。该 Controller 用于开发目的,以输出数据库中的记录列表,该列表将被导入到流量负载生成器中。该工具采用 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;

关于asp.net-web-api - MVC6 Web Api - 返回纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com