且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JsonResult 在 ASP.NET CORE 2.1 中返回 Json

更新时间:2023-02-16 13:00:14

ControllerBase 没有 Json(Object) 方法.但是 Controller代码> 确实如此.

In asp.net-core-2.1 ControllerBase does not have a Json(Object) method. However Controller does.

所以要么重构当前控制器以从 Controller

So either refactor the current controller to be derived from Controller

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

有权访问 Controller.Json 方法 或者你可以初始化一个新的 JsonResult 自己在行动

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

return new JsonResult(rows);

这基本上是该方法在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);
}

来源