简体   繁体   English

从web api帖子返回text \\ plain json响应

[英]returning a text\plain json response from a web api post

I'm having problems with returning a 'text/plain' json response from WebApi. 我在从WebApi返回'text / plain'json响应时遇到问题。
I need to return it as text/plain and by default it returns it as application/json. 我需要将其作为text/plain返回,默认情况下将其作为application / json返回。
The problem I have is exactly what happens in this link . 我遇到的问题正是这个链接中发生的事情。 This isn't a duplicate post since I've read multiple posts but still have a small problem. 这不是一个重复的帖子,因为我阅读了多个帖子,但仍然有一个小问题。

Here's my server code: 这是我的服务器代码:

public HttpResponseMessage Post()
{
       var response = GetModel();
       string jsonRes = JsonConvert.SerializeObject(response);

       var resp = new HttpResponseMessage();
       resp.Content = new StringContent(jsonRes);
       resp.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

       return resp;
}

This is the response I get: 这是我得到的回应:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
  Content-Type: text/plain
}

The jsonRes var contains a valid JSON. jsonRes var包含有效的JSON。
Why is the Content downloaded as Content: System.Net.Http.StringContent ? 为什么内容下载为内容: System.Net.Http.StringContent

I'm probably missing something small here. 我可能在这里错过了一些小东西。

You can do that in this way: 你可以这样做:

  public string Post()
    {
           var response = GetModel();
           string jsonRes = JsonConvert.SerializeObject(response);


           return jsonRes ;
    }

The original question is a bit old, but I had the same problem today, so maybe someone else will be looking for a solution. 最初的问题有点陈旧,但我今天遇到了同样的问题,所以也许其他人会寻找解决方案。 This works for me: 这对我有用:

public HttpResponseMessage Post()
{
   var response = GetModel();
   string jsonRes = JsonConvert.SerializeObject(response);

   var resp = new HttpResponseMessage();
   resp.Content = new StringContent(jsonRes, System.Text.Encoding.UTF8, "application/json");

   return resp;
}

So the "something small" you mentioned is the mediaType parameter in StringContent constructor: 所以你提到的“小东西”是StringContent构造函数中的mediaType参数:

public StringContent (string content, System.Text.Encoding encoding, string mediaType);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM