如何从.Net Core Web API返回Json?

编程入门 行业动态 更新时间:2024-10-26 00:26:16
本文介绍了如何从.Net Core Web API返回Json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个基本问题.我是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?

本文发布于:2023-11-16 19:41:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   Net   Web   Json   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!