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
You basically need to write a custom ActionResult that is indicated here in this post
[HttpGet]
public JsonResult GetUsers()
{
JObject someData = ...;
return new JSONNetResult(someData);
}
The JSONNetResult function is:
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));
}
}
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
You can use ContentResult
instead like this:
return Content(JsonConvert.SerializeObject(...), "application/json");
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<string>
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
return json;
}
or
public ActionResult Movies()
{
var movies = new List<object>();
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);
}
You might want to consider using IHttpActionResult since this will give you the benefit of serialization automatically (or you could do it yourself), but also allows you to control the returned error code in case errors, exceptions or other things happen in your function.
// GET: api/portfolio'
[HttpGet]
public IHttpActionResult Get()
{
List<string> somethings = DataStore.GetSomeThings();
//Return list and return ok (HTTP 200)
return Ok(somethings);
}