JsonResult在ASP.NET CORE 2.1中返回Json

在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);

}

}

在ASP.NET Core 2.1中

return Json (rows);

写道,Json在当前上下文中不存在。如果我们删除Json,就简单地离开

return rows;

然后写道,不可能将类型List()显式转换为JsonResult

如何立即转换为Json?

回答:

在asp.net-core-2.1 ControllerBase中没有Json(Object)方法。但是Controller确实如此。

因此,要么将当前控制器重构为 Controller

public class GraficResourcesApiController : Controller {

//...

}

可以访问该Controller.Json方法,或者您可以JsonResult在操作中初始化一个新的自己

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

}

资源

以上是 JsonResult在ASP.NET CORE 2.1中返回Json 的全部内容, 来源链接: utcz.com/qa/420397.html

回到顶部