With ASP.NET MVC framework, there was a way to do this:
[HttpGet]
public JsonResult GetData()
{
JsonResult result;
InvoiceData dt = new InvoiceData();
result = Json(dt, JsonRequestBehavior.AllowGet);
return result;
}
Now this way is missing – trying to use it results in this error:
Cannot implicitly convert type ‘Microsoft.AspNetCore.Mvc.JsonResult’ to ‘Microsoft.AspNetCore.Mvc.HttpGetAttribute’
I have add only standard .NET Core 8 library in project file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
And don’t add ancient out of support library, but how is possible now return Json result?
2
Answers
In ASP.NET Core,
JsonResult
works differently than in the older versions ofASP.NET MVC
. TheJsonRequestBehavior.AllowGet
option is no longer needed in ASP.NET Core.You need modify your code like below:
Be sure there is no conflict nuget package in your project. Please check both the
Controller
,HttpGetAttribute
andJsonResult
are in theMicrosoft.AspNetCore.Mvc
. TheJson
method belongs toController
class.You can also specify the namespace like below:
Nowadays there’s a lot going on "under the hood" in ASP.NET world.
One of those things is automatic serialization to JSON without you even knowing. Just return
IActionResult
using inherited methodOk
(if you want to return successful 200 repsonse). Of course there are other methods for returning error responses.So, your code will get more simplified to work 🙂