5

I use return Ok(JsonConvert.SerializeObject(res)); to return JSON by my code and this work fine but content type is text/plain

when I use [Produces("application/json")] in my api response be like this:

{\"Value\":\"value1\"}

I need use json serialize, but also need content type application/json.

3 Answers 3

10

If your serialize a string, best to use (as pointed by Marcus)

return Ok(model)

The return type when using Ok method though depends on who your ASP.NET Core application is configured and which formatters are installed (by default only Json Formatter, but you could also install an Xml formatter) and which type the browser prefers. If the browser requests xml and you have xml formatter installed, it will return xml. If the browser requests json and json formatter is installed, it will return json. Otherwise fall back to whatever best suits.

If your data is already serialized as string (cause it comes from DB, filesystem etc.), use

return Content(jsonData, "application/json");

If your data is a file, just use

return PhysicalFile("my.json", "application/json");

If it's a stream

return File(fileStream, "application/json");

etc.

Sign up to request clarification or add additional context in comments.

Comments

4

When you manually serialize the response to json, the framework actually thinks that you are sending a string as response and will therefore add the content type header text/plain to the response. Therefore do not manually serialize the response object.

The easiest way to send objects as json is just to trust the default OutputFormatter which is set to JsonOutputFormatter to do the work. It will serialize all outgoing object responses to json if no other content type is defined on the controller/method/action.

public IActionResult Get()
{
    ...your logic
    return Ok(res);
}

Comments

0

To return Json with the correct content type, return a JsonResult from your method, and then return a JsonResult like this:

// GET: api/authors
[HttpGet]
public JsonResult Get()
{
    return Json(_authorRepository.List());
}

For more information, check this article: Format response data in ASP.NET Core Web API

3 Comments

i should return like this "return Ok()"
Could you explain one thing? Why?
Also: have you looked at the article I linked to? Because there's quite a few scenario's in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.