Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Json from a .Net Core Web API?

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.

The Get() function provided.

    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

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

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.

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

Thank you for your help!

like image 465
PKonstant Avatar asked Jan 27 '23 03:01

PKonstant


1 Answers

Add this attribute to your controller class:

[Produces("application/json")]

So it becomes:

[Produces("application/json")]
public class YourController: Controller {

   [HttpGet]
   public IEnumerable<string> Get()
   {
       return new string[] { "value1", "value2" };
   }
}

That should be enough, otherwise I believe the default is XML (unless the client explicitly asks for JSON using the Accept HTTP header).

like image 189
HaukurHaf Avatar answered Feb 01 '23 19:02

HaukurHaf