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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With