Return JsonResult from WebApi not working ASP.NET

10,542

after some investigation in your code, I really noticed that there are some fundamental errors.

  1. When you are Inheriting from ApiController so here you are creating WebApiController, not MVC controller (which could be created by inheriting from Controller class)

  2. You have to be careful about the namespaces you use because there are some classes and attribute which has the same name but in different namespaces, for example, the HttpPost attribute exists in the System.Web.Http and the System.Web.Mvc and according to your code you have to use the one in the former namespace because you are inheriting from the ApiController.

Keep in mind that the System.Web.Mvc is for ASP.NET MVC and the System.Web.Http is for the Web API.

  1. You are not using the correct return type for the method (which represent Web API method)

So after fixing all the previous problems, the working code should be like this

[System.Web.Http.HttpPost]
public System.Web.Http.IHttpActionResult Post([System.Web.Http.FromBody] CallBackFormModel CallBackFormModel)
{
    // your previous code goes here
    return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}

I recommend you to read about ASP.NET MVC and the Web API and the differences between them to avoid those kinds of problems in the future.

Share:
10,542

Related videos on Youtube

Oscar Dominguez Navarrete
Author by

Oscar Dominguez Navarrete

Updated on June 04, 2022

Comments

  • Oscar Dominguez Navarrete
    Oscar Dominguez Navarrete almost 2 years

    I have a MVC project. I want to get a simple json response {result: "ok"}. Below is my code

    using System;
    using System.Web.Mvc;
    using Microsoft.Xrm.Sdk;
    using CRM_WebApp.Models;
    using System.Web.Http;
    using System.Web.Http.Cors;
    using Microsoft.Xrm.Sdk.Query;
    using CRM_WebApp.Services;
    
    namespace CRM_WebApp.Controllers
    {
        [EnableCors(origins: "*", headers: "*", methods: "*")]
        public class CallBackFormController : ApiController
        {
    
            [System.Web.Mvc.HttpPost]
            public JsonResult Post([FromBody] CallBackFormModel CallBackFormModel)
            {
                ConnectiontoCrm connectiontoCrm = new ConnectiontoCrm();
                //connectiontoCrm.GetConnectiontoCrm();
                connectiontoCrm.GetConnectiontoCrmCopy();
    
                Entity lead = new Entity("lead");
                lead["firstname"] = CallBackFormModel.FirstName;
                lead["mobilephone"] = CallBackFormModel.Telephone;
                lead["telephone3"] = CallBackFormModel.Telephone;
    
                Guid tisa_callbackformid = connectiontoCrm.organizationservice.Create(callbackform);
                return new JsonResult { Data = new { result = "ok" } };
            }
        }
    }
    

    My code gives me the following response:

    {
        "ContentEncoding": null,
        "ContentType": null,
        "Data": {
            "result": "ok"
        },
        "JsonRequestBehavior": 1,
        "MaxJsonLength": null,
        "RecursionLimit": null
    }
    

    How can i change my code to get response: {result: "ok"}

    • Drag and Drop
      Drag and Drop about 6 years
      Your result should be {"result": "ok"} as {result: "ok"} is invalid because string should be wrapped in double quote. Then no matter what the Json is, visual studio special copy past allow you to create the corresponding class. But here i's a bit 'overkill' for a one line json like this one.
  • Oscar Dominguez Navarrete
    Oscar Dominguez Navarrete about 6 years
    I'm getting error: JsonResult does not contain a constructor that take 1 arguments
  • Oscar Dominguez Navarrete
    Oscar Dominguez Navarrete about 6 years
    HI. I'm getting error: Argument 2: Cannot convert from System.Web.Mvc.JsonRequestBehavior to Newtonsoft.Json.JsonSerializerSettings
  • Ehsan Sajjad
    Ehsan Sajjad about 6 years
    return JsonResult(new {result = "ok"}, JsonRequestBehavior.AllowGet);
  • Alexander
    Alexander about 6 years
    While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
  • Hakan Fıstık
    Hakan Fıstık about 6 years
    @OscarDominguezNavarrete I updated the answer for you
  • Oscar Dominguez Navarrete
    Oscar Dominguez Navarrete about 6 years
    @HakamFostok I tried your answer but unsuccessfully(( I'm getting the following error: Cannot implicitly convert type 'System.Web.Http.Results.OkNegotiatedContentResult<<anonymou‌​s type: string result>>' to 'System.Web.Mvc.JsonResult'
  • Hakan Fıstık
    Hakan Fıstık about 6 years
    @OscarDominguezNavarrete see the updated answer again
  • Oscar Dominguez Navarrete
    Oscar Dominguez Navarrete about 6 years
    @HakamFostok Now all is working fine. Thank you for your detailed answer and recommendation. I already start to learn more about MVC and Web API controlleres