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.
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:
public StringContent (string content, System.Text.Encoding encoding, string mediaType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With