Return 来自 WebApi 的 JsonResult 不工作 ASP.NET

Return JsonResult from WebApi not working ASP.NET

我有一个 MVC 项目。我想得到一个简单的 json 响应 {result: "ok"}。下面是我的代码

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

我的代码给出了以下响应:

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

如何更改我的代码以获得响应:{result: "ok"}

试试这个:

return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);

在对您的代码进行一些调查之后,我确实注意到存在一些基本错误。

  1. 当您从 ApiController 继承时,您在这里创建的是 WebApiController,而不是 MVC 控制器(可以通过从 Controller class 继承来创建)

  2. 你必须小心你使用的命名空间,因为有一些 classes 和属性具有相同的名称但在不同的命名空间中,例如 HttpPost 属性存在于 System.Web.HttpSystem.Web.Mvc 中,根据您的代码,您必须使用前一个命名空间中的属性,因为您继承自 ApiController.

请记住,System.Web.Mvc 适用于 ASP.NET MVC,System.Web.Http 适用于 Web API。

  1. 您没有使用正确的 return 方法类型(表示 Web API 方法)

所以在解决了之前所有的问题之后,工作代码应该是这样的

[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);
}

我建议您阅读 ASP.NET MVC 和 Web API 以及它们之间的区别,以避免将来出现此类问题。

为了回答你的问题,我遇到了同样的问题,因为当我 return 一个回复时,我喜欢 return 多个 objects/types。

例如,我总是 return 包含一些成功和错误消息的消息结果。这个对象在我所有的 api 回复中几乎被重复使用。然后我想 return 第二个对象包含任何数据,例如客户列表或其他任何数据。

这就是我让它在 WebAPI 上工作的方式...

public IHttpActionResult DeleteEmailTemplate(int id)
    {
        FormResponse formResponse = new FormResponse("SUCESS MESSAGE HERE");

        List<string> strings = new List<string>();
        strings.Add("this is a test");
        strings.Add("this is another test");

        return Json(new { MessageResult = formResponse, TestObject = strings });
    }