要在 ASP .Net Core 控制器中发送 Json 原始内容,可以使用 JsonResult 对象。以下是一个示例控制器方法:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
// Create a JObject with some data
JObject data = new JObject();
data["foo"] = "bar";
data["baz"] = 123;
// Serialize the JObject to a string
string jsonString = data.ToString();
// Return a JsonResult with the serialized JSON string as the content
return new JsonResult(jsonString);
}
}
此控制器方法将创建一个包含一些数据的 JObject,将 JObject 序列化为字符串,然后将字符串作为 JsonResult 返回。另外,要注意必须使用 return new JsonResult(jsonString)
的方式来返回 Json 原始内容,而不能简单地使用 return jsonString
。