ASP MVC 5和Json.NET:动作返回类型

我正在使用ASP MVC 5.我在控制器中有一个返回json对象的动作:

[HttpGet] public JsonResult GetUsers() { return Json(....., JsonRequestBehavior.AllowGet); } 

现在我想使用JSON.Net库,我发现在ASP MVC 5中还存在。 实际上我可以写

 using Newtonsoft.Json; 

没有从NuGet导入库。

现在我试着写:

 public JsonResult GetUsers() { return JsonConvert.SerializeObject(....); } 

但是我在编译期间出错:我无法将返回类型字符串转换为JsonResult。 我怎样才能在动作中使用Json.NET? 动作的正确返回类型是什么?

您可以使用ContentResult如下所示:

 return Content(JsonConvert.SerializeObject(...), "application/json"); 

我更喜欢创建一个对象扩展来创建一个自定义的Action Result,这就是我选择的原因……

对象扩展(我的具体情况,我使用newtonsoft进行序列化并忽略空值:

 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; } } 

并且它非常容易使用,它可以扩展到任何对象,所以使用它只需要它:

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

希望它对任何人都有帮助

 public string GetAccount() { Account account = new Account { Email = "james@example.com", Active = true, CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), Roles = new List { "User", "Admin" } }; string json = JsonConvert.SerializeObject(account, Formatting.Indented); return json; } 

要么

 public ActionResult Movies() { var movies = new List(); movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984 }); movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 }); movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 }); return Json(movies, JsonRequestBehavior.AllowGet); } 

您基本上需要编写此post中指出的自定义ActionResult

 [HttpGet] public JsonResult GetUsers() { JObject someData = ...; return new JSONNetResult(someData); } 

JSONNetResult函数是:

 public class JSONNetResult: ActionResult { private readonly JObject _data; public JSONNetResult(JObject data) { _data = data; } public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ContentType = "application/json"; response.Write(_data.ToString(Newtonsoft.Json.Formatting.None)); } } 

您可能需要考虑使用IHttpActionResult,因为这将为您提供自动序列化的好处(或者您可以自己完成),但也允许您控制返回的错误代码,以防您的函数中发生错误,exception或其他事情。

  // GET: api/portfolio' [HttpGet] public IHttpActionResult Get() { List somethings = DataStore.GetSomeThings(); //Return list and return ok (HTTP 200) return Ok(somethings); }