JsonResult return Json in ASP.NET CORE 2.1

后端 未结 1 1499
长发绾君心
长发绾君心 2020-12-10 10:35

Controller that worked in ASP.NET Core 2.0:

[Produces(\"application/json\")]
[Route(\"api/[controller]\")]
[ApiController]
public class GraficResourcesApiCon         


        
相关标签:
1条回答
  • 2020-12-10 11:09

    In asp.net-core-2.1 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

    0 讨论(0)
提交回复
热议问题