PKo*_*ant 4 c# json.net asp.net-core-webapi
这是一个基本问题。我是 ASP.Net Core 的新手,所以我使用 Visual Studio 2017 中的模板创建了一个 .Net Core Web API 项目,我想知道如何从 Get() 函数返回 Json 字符串。
提供了 Get() 函数。
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何更改,以便它返回如下所示的 int 变量的 Json 字符串。
// GET: api/MOER
[HttpGet]
public <<some return type>> Get()
{
_MOER = 32;
return <<return a Json result/string of _MOER>>;
}
Run Code Online (Sandbox Code Playgroud)
我已经看到 Nuget 包 Newtonsoft.Json 在其中进行序列化/反序列化,但我不确定它是否适用于 .Net Core。
我也看到过使用 JsonResult 的例子,但是当我尝试使用这种方法时,编译器不知道 Json() 是什么。
[HttpGet]
public JsonResult Get()
{
_MOER = 32;
return Json(_MOER);
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!
将此属性添加到您的控制器类:
[Produces("application/json")]
Run Code Online (Sandbox Code Playgroud)
所以就变成了:
[Produces("application/json")]
public class YourController: Controller {
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Run Code Online (Sandbox Code Playgroud)
这应该足够了,否则我认为默认值是 XML(除非客户端使用 Accept HTTP 标头明确要求 JSON)。