ASP MVC 5 and Json.NET: action return type

后端 未结 5 2107
闹比i
闹比i 2021-01-19 23:14

i\'m using ASP MVC 5. I have an action in a controller that return a json object:

[HttpGet]
public JsonResult GetUsers()
{
  return Json(....., JsonRequestBe         


        
5条回答
  •  清歌不尽
    2021-01-20 00:09

    I prefer to create an object extension to create a custom Action Result, and this is the reason for my choose...

    The Object Extension (My specific case, i am serializing with newtonsoft and ignoring null values:

    public static class NewtonsoftJsonExtensions
    {
        public static ActionResult ToJsonResult(this object obj)
        {
            var content = new ContentResult();
            content.Content = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            content.ContentType = "application/json";
            return content;
        }
    }
    

    And it's really easy to use, sinse its extensible to any object, so to use u just need it:

        public ActionResult someRoute()
        {
            //Create any type of object and populate
            var myReturnObj = someObj;
            return myReturnObj.ToJsonResult();
        }
    

    hope it's being helpful for anyone

提交回复
热议问题