MVC6 Web Api - Return Plain Text

▼魔方 西西 提交于 2019-12-08 02:55:51

问题


I have looked at other similar questions (such as this one Is there a way to force ASP.NET Web API to return plain text?) on SO but they all seem to address WebAPI 1 or 2, not the latest version you use with MVC6.

I need to return plain text on one of my Web API controllers. Only one - the others should keep returning JSON. This controller is used for dev purposes to output a list of records in a database, which will be imported into a traffic load generator. This tool takes CSV as input so I'm trying to output that (users will only have to save the content of the page).

[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;
}

Based on various searches this seems like the simplest way to proceed since I'll need this only for this one action. However when I request this, I get the following output:

{
   "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
}

So it seems that MVC still tries to output JSON, and I have no idea why they'd output these values. When I debug the code step by step I can see that the content of the StringBuilder is okay and what I want to output.

Is there any easy way to just output a string with MVC6?


回答1:


Have a go with this:

var httpResponseMessage = new HttpResponseMessage();

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

return httpResponseMessage;



回答2:


The solution was to return a FileContentResult. This seems to bypass the built-in formatters:

[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");
}


来源:https://stackoverflow.com/questions/35749928/mvc6-web-api-return-plain-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!