如何从.Net Core Web API返回Json? [英] How to return a Json from a .Net Core Web API?
问题描述
这是一个基本问题.我是ASP.Net Core的新手,所以我使用Visual Studio 2017中的模板创建了一个.Net Core Web API项目,我想知道如何从Get()函数返回Json字符串.
This is a basic question. I am new to ASP.Net Core so I created a .Net Core Web API project using the template in Visual Studio 2017 and I would like to know how to return a Json string from the Get() function.
提供了Get()函数.
The Get() function provided.
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
我想知道如何更改,以便它返回一个int变量的Json字符串,如下所示.
I would like to know how to change so it returns a Json string of int variable like the following.
// GET: api/MOER
[HttpGet]
public <<some return type>> Get()
{
_MOER = 32;
return <<return a Json result/string of _MOER>>;
}
我已经看到了Nuget包Newtonsoft.Json,您可以在其中进行序列化/反序列化,但是我不确定它是否适用于.Net Core.
I am have seen the Nuget package Newtonsoft.Json where you serialize/deserialize but I am not sure if its applicable any more with .Net Core.
我也看到了使用JsonResult的示例,但是当我尝试使用这种方法时,编译器不知道Json()是什么.
I have also seen examples where they use JsonResult but when I try to use this approach, the compiler doesn't know what Json() is.
[HttpGet]
public JsonResult Get()
{
_MOER = 32;
return Json(_MOER);
}
谢谢您的帮助!
推荐答案
将此属性添加到控制器类:
Add this attribute to your controller class:
[Produces("application/json")]
它变成:
[Produces("application/json")]
public class YourController: Controller {
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
那应该足够了,否则我相信默认值是XML(除非客户端使用Accept HTTP标头明确要求JSON).
That should be enough, otherwise I believe the default is XML (unless the client explicitly asks for JSON using the Accept HTTP header).
这篇关于如何从.Net Core Web API返回Json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!