0

I am getting an error whenever I try to call a custom api function in c# asp.net core. The Error code I am getting

Cannot implicitly convert type MnrtPortal.Helpers.CustomApiResponse to Microsoft.AspNetCore.Mvc.IActionResult an explicit conversion exists.

 [Route("api/User")]
        public IActionResult User()
        {
            var user = new
            {
                Name = "Joshua",
                Age = 40
            };
            // return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
            return CustomApiResponse.Create(200,user,"success");
        }
Jéf Bueno
  • 425
  • 1
  • 5
  • 23
BAKARI SHEGHEMBE
  • 449
  • 6
  • 20
  • What is `CustomApiResponse` ? – Shyju Jan 25 '18 at 15:47
  • It is a custom function that I have defined to handle my api responses – BAKARI SHEGHEMBE Jan 25 '18 at 15:48
  • Is that class which has a Create method ? What does that do ? You need to share that! – Shyju Jan 25 '18 at 15:49
  • You should return an `IActionResult` – Jéf Bueno Jan 25 '18 at 15:52
  • Your `CustomApiResponse.Create` returns `CustomApiResponse` object.But your action method signature is defined as `IActionResult`. Change it to `public CustomApiResponse User()` – Shyju Jan 25 '18 at 15:52
  • There are plenty of posts on returning custom results from MVC controllers like https://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html as well as plenty of posts explaining conversion error... Could you please clarify what type of new information you are looking for in this question? – Alexei Levenkov Jan 25 '18 at 16:00

1 Answers1

1

CustomApiResponse doesn't implement IActionResult, so you cannot return it directly in a method that returns IActionResult. Pretty straight-forward.

You can either change the return type of the action to CustomApiResponse, which should trigger the default serializer (JSON) and cause a JsonResult to be created from that. Or you can simply wrap your object in an OkObjectResult which will have the same effect.

return Ok(CustomApiResponse.Create(200,user,"success"));

Finally, you can explicitly return a JsonResult if you prefer via:

return Json(CustomApiResponse.Create(200,user,"success"));
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Thanks it worked, but now I need additional help to pass the status code – BAKARI SHEGHEMBE Jan 25 '18 at 16:01
  • 1
    Because your method takes `HttpStatusCode` enum, not an int (which is what you are passing). Replace 200 with `HttpStatusCode.OK`. But i strongly suggest you refresh your basic C# knowledge about classes,methods types etc before trying to build anything. – Shyju Jan 25 '18 at 17:25