Search code examples
c#jsonasp.net-mvcasp.net-core

How to return JSON result in ASP.NET Core 8 project


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?


Solution

  • In ASP.NET Core, JsonResult works differently than in the older versions of ASP.NET MVC. The JsonRequestBehavior.AllowGet option is no longer needed in ASP.NET Core.

    You need modify your code like below:

    public class HomeController : Controller
    {    
        [HttpGet]
        public JsonResult GetData()
        {
            JsonResult result;
            InvoiceData dt = new InvoiceData();
            result = Json(dt);
            return result;
        }
    }
    

    Be sure there is no conflict nuget package in your project. Please check both the Controller,HttpGetAttribute and JsonResult are in the Microsoft.AspNetCore.Mvc. The Json method belongs to Controller class.

    enter image description here

    enter image description here enter image description here

    enter image description here

    You can also specify the namespace like below:

    public class HomeController : Microsoft.AspNetCore.Mvc.Controller
    {    
        [Microsoft.AspNetCore.Mvc.HttpGet]
        public Microsoft.AspNetCore.Mvc.JsonResult GetData()
        {
            Microsoft.AspNetCore.Mvc.JsonResult result;
            InvoiceData dt = new InvoiceData();
            result = Json(dt);
            return result;
        }
    }