Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a text\plain json response from a web api post

I'm having problems with returning a 'text/plain' json response from WebApi.
I need to return it as text/plain and by default it returns it as 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.
Why is the Content downloaded as Content: System.Net.Http.StringContent?

I'm probably missing something small here.

like image 593
Amir Popovich Avatar asked Sep 22 '26 00:09

Amir Popovich


2 Answers

You can do that in this way:

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


           return jsonRes ;
    }
like image 125
sylwester Avatar answered Sep 24 '26 14:09

sylwester


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:

public StringContent (string content, System.Text.Encoding encoding, string mediaType);
like image 28
skan Avatar answered Sep 24 '26 14:09

skan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!