skip to Main Content

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


  1. 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;
        }
    }
    
    Login or Signup to reply.
  2. 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 method Ok (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 🙂

    [HttpGet]
    public IActionResult GetData()
    {
        JsonResult result;
        InvoiceData dt = new InvoiceData();
        return Ok(dt);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search