Return JsonResult from WebApi not working ASP.NET

Oscar Dominguez Navarrete picture Oscar Dominguez Navarrete · Mar 19, 2018 · Viewed 8.7k times · Source

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"}

Answer

Hakan Fıstık picture Hakan Fıstık · Mar 19, 2018

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.