"return Json(jsonData)" vs "return content (jsonData, "application/json")"

john john 966 Reputation points
2022-10-15T01:52:45.843+00:00

I have this code inside an ASP.NET MVC-5 action method, which serialize an object as JSON using Newtonsoft package:-

string jsonData = JsonConvert.SerializeObject(result);  

and i can return the above JSON using this return statement:-

return Json(output,JsonRequestBehavior.AllowGet);  

Or using this return statement:-

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

so are there really any differences between the two methods return Json(jsonData) vs return content (jsonData, "application/json") ? and which one we should use to return the already serialized json object ?

Thanks

Now when i call the action method from firefox, i will get this json in case i use return Json(output,JsonRequestBehavior.AllowGet):-

![250686-image.png

while i will get this json (which seems to be the accurate one) when using return Content(output,"application/json"):-

250658-image.png

so seems the json i will get when using return Content(output,"application/json"); is the accurate one? while using return json(output,JsonRequestBehavior.AllowGet); will return string that can not be understandable by firefox?

Thanks

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,510 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 28,536 Reputation points
    2022-10-15T15:06:29.97+00:00

    Your design serializes twice. First, an object is converted to JSON. Next, the JSON is converted to a string.

    The standard pattern in MVC 5 (.NET Framework) is defining a ActionResult return type and simply returning a type and letting the framework serialize the type. I believe MVC 5 uses Newtonsoft by default.

    namespace MvcDemo.Controllers  
    {  
        public class ViewModel  
        {  
            public string Message { get; set; }  
        }  
      
        public class HomeController : Controller  
        {  
            [HttpGet]  
            public ActionResult Index()  
            {  
                ViewModel model = new ViewModel() { Message = "Hello world" };  
                return Json(model, JsonRequestBehavior.AllowGet);  
            }  
        }  
    }  
    

    I recommend Web API rather than MVC for returning JSON.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.