Web Api控制器无法识别Json方法

我有一个web api控制器

using sport.BLL.Abstract; using sport.BLL.Concrete; using sport.DAL.Entities; using sport.webApi.Models; using AutoMapper; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web; using System.Web.WebPages.Html; namespace sport.webApi.Controllers { public class AccountManageController : ApiController { [HttpPost] public System.Web.Mvc.ActionResult CreateAccount(CollaborateurModel item) { var user = new ApplicationUser { UserName = item.Username, Email = item.Email }; var result = UserManager.CreateAsync(user, item.Password); if (result.Result.Succeeded) { var currentUser = UserManager.FindByName(item.Username); var roleresult = UserManager.AddToRole(currentUser.Id, item.Role); ajt_collaborator entity = Mapper.Map(item); entity.id_user_fk = currentUser.Id; entity.is_deleted = false; repo.CreateCollaborator(entity); var response = new { Success = true }; return Json(response); } else { var errorResponse = new { Success = false, ErrorMessage = "error" }; return Json(errorResponse); } } } } 

我在这行中遇到错误:

返回Json(回应);

Json方法无法识别!!! 当我用google搜索时,我得到了这个链接 ,表明Json方法包含在System.Web.Mvc 。 即使我尝试导入此命名空间,我得到相同的错误?

  1. 这个错误的原因是什么?
  2. 我该如何解决?

问题是您inheritance自ApiControllerJsonSystem.Web.Mvc.Controller的成员。

尝试使用JsonResult

 return new JsonResult { data = yourData; } 

您可以将任何对象设置为数据,因为它将被序列化为JSON。

例如,如果只需要返回操作结果,可以这样使用它:

 return new JsonResult { data = true; } // or false 

但是,描述结果类和返回对象是一种好习惯。

我该如何解决?

原因在于你不是从Controllerinheritance而是从ApiControllerinheritance,前者将Json(object o)作为其基类中的方法,但这实际上并不重要,因为存在一个基本问题你的方法。

与WebAPI一起使用的ApiController并不意味着返回ActionResult ,这是一个属于MVC的概念。 相反,您只需返回您的POCO并让WebAPI框架为您处理序列化:

 public object CreateAccount(CollaborateurModel item) { // Do stuff: if (result.Result.Succeeded) { return new { Success = true } } else { return new { Success = false, ErrorMessage = "error" }; } } 

您可以在Global.asax.cs文件中设置格式化程序配置 ,并准确告诉它使用哪些(在您的情况下,您将需要JsonMediaTypeFormatter )。