JsonResult return Json in ASP.NET CORE 2.1
Asked Answered
S

1

28

Controller that worked in ASP.NET Core 2.0:

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class GraficResourcesApiController : ControllerBase
{    
    private readonly ApplicationDbContext _context;

    public GraficResourcesApiController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public JsonResult GetGrafic(int ResourceId)
    {
        var sheduling = new List<Sheduling>();


        var events = from e in _context.Grafic.Where(c=>c.ResourceId == ResourceId)
                     select new
                     {
                         id = e.Id,
                         title = e.Personals.Name,
                         start = e.DateStart,
                         end = e.DateStop,
                         color = e.Personals.Color,
                         personalId = e.PersonalId,
                         description = e.ClientName
                     };
        var rows = events.ToArray();

        return Json(rows);
    }
}

in ASP.NET Core 2.1

return Json (rows);

writes that Json does not exist in the current context. If we remove Json leaving simply

return rows;

then writes that it was not possible to explicitly convert the type List () to JsonResult

How to convert to Json now?

Sulfide answered 30/8, 2018 at 15:53 Comment(0)
S
52

In ControllerBase does not have a Json(Object) method. However Controller does.

So either refactor the current controller to be derived from Controller

public class GraficResourcesApiController : Controller {
    //...
}

to have access to the Controller.Json Method or you can initialize a new JsonResult yourself in the action

return new JsonResult(rows);

which is basically what the method does internally in Controller

/// <summary>
/// Creates a <see cref="JsonResult"/> object that serializes the specified <paramref name="data"/> object
/// to JSON.
/// </summary>
/// <param name="data">The object to serialize.</param>
/// <returns>The created <see cref="JsonResult"/> that serializes the specified <paramref name="data"/>
/// to JSON format for the response.</returns>
[NonAction]
public virtual JsonResult Json(object data)
{
    return new JsonResult(data);
}

/// <summary>
/// Creates a <see cref="JsonResult"/> object that serializes the specified <paramref name="data"/> object
/// to JSON.
/// </summary>
/// <param name="data">The object to serialize.</param>
/// <param name="serializerSettings">The <see cref="JsonSerializerSettings"/> to be used by
/// the formatter.</param>
/// <returns>The created <see cref="JsonResult"/> that serializes the specified <paramref name="data"/>
/// as JSON format for the response.</returns>
/// <remarks>Callers should cache an instance of <see cref="JsonSerializerSettings"/> to avoid
/// recreating cached data with each call.</remarks>
[NonAction]
public virtual JsonResult Json(object data, JsonSerializerSettings serializerSettings)
{
    if (serializerSettings == null)
    {
        throw new ArgumentNullException(nameof(serializerSettings));
    }

    return new JsonResult(data, serializerSettings);
}

Source

Submerge answered 30/8, 2018 at 16:29 Comment(4)
So upgrading from 2.0 to 2.1 breaks existing code. Anyone know why they changed this?Refresher
@Refresher I coulldn't tell you why they changed it, but I can tell you that one of the main reasons behind DNC was that they could break things. Fast iterations with little promise of backwards compatibility.Lightproof
Note that if you are creating an API it is recommended in the docs not to use Controller, but ControllerBase. Ref docs: Don't create a web API controller by deriving from the Controller class. Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and APIs, derive it from Controller.Disproportionation
That's fine but returning JSON is a fundamental API activity, so it seems unusual that it's not a member of the class they're recommending for APIs.Camerlengo

© 2022 - 2024 — McMap. All rights reserved.