I had a function app in C# that made a function call to a stored procedure and returned the results as follows:
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(reader);
jsonstring = JsonConvert.SerializeObject(dataTable);
connection.Close();
return new OkObjectResult(jsonstring);
When I moved this code to >NET CORE I get the following error message: CS0029: Cannot implicitly convert type Microsoftaspnetcore.mvc.OkObjectResult to Microsoftaspnetcore.mvc.JsonResult
But if I switch to JsonResult(jsonstring) then my application thows this error: Error parsing JSON data: SyntaxError: Unexpected end of JSON when I run JSON.parse(data)
I have tried different formats but that did not help.
With JsonResult(jsonstring)
, you are returning the response with JSON array string as below:
"[/* JSON objects */]"
Instead of returning JSON in string, you should return the array as:
using Newtonsoft.Json.Linq;
public JsonResult YourApiAction(/* arguments */)
{
...
return new JsonResult(JArray.FromObject(dataTable));
}
Or you can return the dataTable
directly. It will be serialized as a JSON array.
public JsonResult YourApiAction(/* arguments */)
{
...
return new JsonResult(dt);
}
Side note, if your Controller class inherits Controller
as the base class, you can use the Json
method.
public class YourController : Controller
{
public JsonResult YourApiAction(/* arguments */)
{
...
return Json(dt);
}
}